Removing last comma from a foreach loop

痴心易碎 提交于 2019-11-27 08:28:05

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>

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;
}

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.

Alternatively to @Sébastien's answer, you could do this:

echo "<span>".ucfirst($this->sinonimo[0]);
for($i = 1; $i < count($this->sinonimo); $i++) {
    echo "</span>, <span>" . ucfirst($this->sinonimo[$i]);
}
echo "</span>";

This doesn't need the extra array. It works by first printing the first element, then in the loop printing the intermediate segment followed by the next element, and then closes everything off with the end segment.

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

u can use trim function. suppose your string is like this

$str=1,2,3,4,5,6,7,8,

u can try this

echo trim($str, ",");

and the output is

1,2,3,4,5,6,7,8

use substr() function

Put your final string in substr() function

 $string = "";
    while ($row = mysql_fetch_array($result)) {
      $string .= $name . ', ';
    }
    echo substr($string, 0, strlen($string) - 2);

Laravel implode() function for relational data.

Like post has many categories.

$user->posts->implode('categories.name', ', '); // In loop {{  $post->categories->name }}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!