1
I have a loop that is generating several names, but need the result of this loop is merged into only one string and names are separated by commas, but omitting the comma in the last name.
Expected example:
Nome 1, Nome 2, Nome 3, Nome 4
I’m using the following loop to generate the strings names.
The code:
$nomes = "";
foreach ($valor_array->nome as $nome) {
$nomes .= $nome . ", ";
}
echo $nomes;
How could I do this without generating a string with a comma in the last word like Nome 1, Nome 2, Nome 3, Nome 4,
?
Is there more than one way to do this? What would be?
As stated in the other posts, a
echo rtrim( $nomes, ', ' );
That’s what you want. Actually, if you take my answer as the basis in the original, just add the concept of $separator to your own, if you need something more complex in the future (like commas and quotes, for example).– Bacco
Another simple exit in your case is
$nomes=array(); foreach( $valor_array->nome as $nome) $nomes[] = $nome; echo implode( ', ', $nomes );
(this assuming they are objects) - probably, if it is array, only one line is enough, without any loop:echo implode( ', ', $valor_array->nome );
– Bacco
Thanks for link the question, had not found the way I researched.
– Florida