Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Build comma separated string in PHP Loop [duplicate]

Tags:

arrays

loops

php

Hello Guys i need to do this,

I have a common loop

foreach ($stuffs as $stuff) {
echo $stuff;
}

Lets assume $stuff is an 'id' of a mysql table what i have and i dont want to be showed in next results, so i want to build a string like this

1,23,54,67 (comma separated) 

So that string will be in mysql query to exclude results that already have been shown. how can i do that?

Should be with implode? How can i achieve that?

like image 592
Paulo José Oliveira Rosa Avatar asked Jul 09 '26 19:07

Paulo José Oliveira Rosa


2 Answers

implode should be the tool:

implode(",", $stuffs);

will return a comma separated list.

Test

$myarray=array(1,2,"hello",4,5);
echo implode(",", $myarray);

returns

1,2,hello,4,5
like image 145
fedorqui 'SO stop harming' Avatar answered Jul 14 '26 13:07

fedorqui 'SO stop harming'


If you really wanna have the loop:

$values = "";

foreach ($stuffs as $stuff) {
    $values != "" && $values .= ",";
    $values .= $stuff;
 }

echo $values;

I suggest using implode, but the loop can really give you more power if you wanna do some further stuff.

like image 30
Hosea Kambonde Avatar answered Jul 14 '26 14:07

Hosea Kambonde



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!