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?
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:
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.