I can’t get my head around how to change what is outputed for the last item in a foreach
loop in php. I have the code below which renders well, but I want to remove the comma from after the last item that is rendered in the foreach
loop.
if(!empty($terms)){
foreach($terms as $term){
echo $term->name.', ';
}
}
How can I modify this to render the last item in the loop without the ', '
bit?
If someone can explain and show me that would be great so I can learn how it works.
4
Answers
I changed my approach here and added a around each item rendered from the foreach loop and then used CSS to add a comma to all but the last-of-type - this way worked more logically for my visual brain ;)
You could use
array_column
to get all "name" values, and thenimplode
to make one string. Then remains toecho
it…You cannot remove the text after you’ve emitted it, obviously.
So you need to not emit it in the first place.
One way is to send the separator before each item except the first, instead of after each item except the last, because determining the first item is simpler – and actually can be coded using the separator itself:
(You do not need the check
empty($terms)
).The above approach is useful if you have more levels of nesting (for example, you have a series of rows that need to be grouped by city, contractor and contract number, and your "separator" is a row of subtotals): instead of
$sep
you’ll have an array$sep[$nestingLevel]
, which can hold a fixed separator string or an array of subtotals.In the simplest case when you want a straight concatenation of items, you can do this with
implode()
, that does the same thing: