6

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?

  • 1
    Possible duplicate of [How to create comma separated list from array in PHP?](https://stackoverflow.com/questions/2435216/how-to-create-comma-separated-list-from-array-in-php) – mickmackusa Feb 19 '18 at 13:26

4 Answers4

19

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
fedorqui
  • 275,237
  • 103
  • 548
  • 598
4

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.

mixel
  • 25,177
  • 13
  • 126
  • 165
Hosea Kambonde
  • 291
  • 1
  • 4
  • 13
3

This worked in my case (detects if isn't the loop last iteration):

foreach($array as $key => $val){
    ...
    if($key!==count($array)-1){echo ',';}
}
neoDev
  • 2,879
  • 3
  • 33
  • 66
0

Should be as simple as:

$string = implode(",",$stuffs);
echo $string
J.Michieli
  • 91
  • 9