从foreach循环中删除最后一个逗号 [英] Removing last comma from a foreach loop

查看:656
本文介绍了从foreach循环中删除最后一个逗号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


$ b使用foreach循环来回显我的数据库中的一些值,并用逗号分隔每个值,但是我不知道如何去除最后一个逗号。 $ b

我的代码很简单,但我似乎无法找到这样做的正确方法:

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

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




$ p
$ b

感谢您的帮助:)

解决方案

把你的值放在一个数组中,然后用逗号(+

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

echo implode(',',$ myArray);

这会在每个值之间插入逗号,但不会结束。在这种情况下,逗号将超出范围,例如:

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


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 :)

解决方案

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>

这篇关于从foreach循环中删除最后一个逗号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆