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 :)
An alternative method of removing the comma from last foreach loop item. In this alternative way, we are going to use the PHP array_push() function. below is the code: <?
To remove the last comma from a string, call the replace() method with the following regular expression /,*$/ as the first parameter and an empty string as the second. The replace method will return a new string with the last comma removed.
You actually don't need the foreach loop. Just pass the array to implode - it'll only add a comma if there's more than one element.
break ends execution of the current for , foreach , while , do-while or switch structure. break accepts an optional numeric argument which tells it how many nested enclosing structures are to be broken out of. The default value is 1 , only the immediate enclosing structure is broken out of.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With