从 foreach 循环中删除最后一个逗号 [英] Removing last comma from a foreach loop
问题描述
我使用 foreach 循环从我的数据库中回显一些值并用逗号分隔每个值,但我不知道如何删除它在最后一个值上添加的最后一个逗号.
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 :)
推荐答案
把你的值放在一个数组中,然后用逗号(+ 一个空格更干净)implode
该数组:
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屋!