Removing last comma from a foreach loop

MONZTAAA picture MONZTAAA · Nov 12, 2013 · Viewed 20.5k times · Source

Im using a foreach loop to echo out some values from my database and seperating each of them by commas but I dont know how to remove the last comma it adds on the last value.

My code is pretty simple but I just cant seem to find the correct way of doing this:

foreach ($this->sinonimo as $s){ 

echo '<span>'.ucfirst($s->sinonimo).',</span>';

}

Thanks in advance for any help :)

Answer

S&#233;bastien picture Sébastien · Nov 12, 2013

Put your values in an array and then implode that array with a comma (+ a space to be cleaner):

$myArray = array();
foreach ($this->sinonimo as $s){ 
    $myArray[] = '<span>'.ucfirst($s->sinonimo).'</span>';
}

echo implode( ', ', $myArray );

This will put commas inbetween each value, but not at the end. Also in this case the comma will be outside the span, like:

<span>Text1<span>, <span>Text2<span>, <span>Text3<span>