John Sheridan
John Sheridan

Reputation: 92

Variable that changes its value at end of foreach()

I'm trying to flow some information from the database into HTML to display for my users. I'd like to print new tags each time the "industry" changes. I'm trying to use a variable called $last_industry to track whether or not the industry I'm currently iterating over is equal to the last one, but I'm not having good results. I've pasted my code below. $c['user_industries_title'] is what I need to monitor.

$last_industry = 'foo';

foreach($case_studies as &$c) {
  //If the last industry we iterated over is different than the one we're currently iterating over, close the last section and print a new section.
  if($last_industry != $c['user_industries_title']){
    echo "</section>"  
    echo "<section>";
    $changed = 1;
  }else {$changed = 0}

  $c = $last_industry;
  $last_industry = $c['user_industries_title'];
}

This issue is with the $last_industry variable. For this to work, it needs to update itself to the most recent $c['user_industries_title'] for use back at the beginning of the next iteration, which is not happening. Am I missing something?

Upvotes: 0

Views: 84

Answers (2)

Jonas Osburg
Jonas Osburg

Reputation: 1783

Have a look at the last two lines, you override your $c which is an array with $last_industry which is the string you used in the last iteration. Rename the $c in the 2nd last line or remove it completely.

BTW: If you set your PHP error_reporting settings to E_ALL you would have been notified, that $c is not an array anymore!

Upvotes: 1

Marc B
Marc B

Reputation: 360762

You need to change the $last_industry value inside the if() when the value has changed, otherwise you're always running with the same industry value:

$last_industry = null;

foreach ($case_studies as $c) {
   if ($last_industry != $c['user_industries_title']) {
      echo '</section><section>';
      $last_industry = $c['user_industries_title'];
      $changed = 1;
   } else {
      $changed = 0;
   }
}

Also, be aware of a pitfall in making $c a reference (& operator) - it'll remain a reference for the duration of the script and can cause odd sideeffects if you depend on it maintaining its value after the loop exits.

Upvotes: 2

Related Questions