Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing last comma from a foreach loop

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

like image 527
MONZTAAA Avatar asked Nov 12 '13 17:11

MONZTAAA


People also ask

How do you remove the last comma in a for loop?

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

How do I remove the last comma character from a string?

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.

How do you put a comma in a foreach loop?

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.

Does Break exit foreach?

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.


2 Answers

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>
like image 58
Sébastien Avatar answered Sep 24 '22 03:09

Sébastien


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;
}
like image 26
Jorge Campos Avatar answered Sep 23 '22 03:09

Jorge Campos