I’m running a foreach inside another foreach so I can display categories associated with each venue.
Once I place the $comboClass outside of the foreach loop - I only get the last category from the variable. But if I leave it within, I see all the categories - shown below the result.
How do I print all the categories $comboClass within the span?
Why is it only printed the last category?
Please note:
The code above is just at testing stage right now. Once I understand the problem, I will be adding the $comboClass inside the <li class="' .$comboClass . '">
If you look at this line: $comboClass = $cat . " "; you’re actually reassigning the value of $comboClass for every iteration of the loop. What you want to be doing is concatenating the values, like this: $comboClass .= $cat . " "; (notice the concatenation operator immediately before the equals symbol).
This will generate a PHP notice though, as $comboClass doesn’t exist on the first iteration of the loop. To solve this, you can declare it before the foreach loop and assign it an empty string.
Personally, though, I’d do this with an array rather than string concatenation:
The benefit of this method is that it’s an easy way to ensure you only get separator characters between each item. It also makes it easy to process the array before outputting the final string, e.g. to sort or remove duplicates etc.
Arrrh! Yes - I recall seeing this and thought nothing of it.
Good catch
This is working great @fretburner thanks for the examples - I’ve managed to get things working how I need it (shown below).
I realised this as the final category had a trailing space. This has tidied things up. I had both ways setup, though as you say better with the array() which I finally used.