Removing last comma from a foreach loop

Solution 1:

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>

Solution 2:

Another approach for your code would be a bit logic:

hasComma = false;
foreach ($this->sinonimo as $s){ 
    if (hasComma){ 
        echo ","; 
    }
    echo '<span>'.ucfirst($s->sinonimo).'</span>';
    hasComma=true;
}

Solution 3:

I'll generally try to avoid adding logic for such use cases. The best method would be to store the values in an array and implode it with a comma.

However, you can add the commas by CSS which is much easier.

Your nice and clean loop:

foreach($collection->object as $data)
{
    echo "<span>" . $data->var . "</span>";
}

And for the CSS:

.selector span:after {
    content: ",";
}
.selector span:last-child:after {
    content: "";
}

This works for all major browsers including IE8 and newer.

Solution 4:

Laravel has a implode() function same as php implode().

You should use implode() function on Collection object:

$user->posts->implode('title', ', ');

output will be something like this:

Hello world!, First post, Second post