7

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?

0

4 Answers 4

20

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
Sign up to request clarification or add additional context in comments.

5 Comments

+1 cannot see what's wrong with this (ps. well, you could use ' instead of ", which in theory would be faster)
this makes an assumption that $stuffs is already an array, whereas it doesnt have to be that way. It can be something else that is iterable
@Gadoma - though if $stuffs wasn't an array, OP should have indicated that in their question
Ops new solution tryin here folks leme check
@MarkBaker true, true :)
5

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.

2 Comments

Well if you really wanna have the loop - why would you wanna have the loop in the first place? It's not necessary here. A simple implode() would do the job ;)
Like I said, just gives you more control
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 ',';}
}

Comments

0

Should be as simple as:

$string = implode(",",$stuffs);
echo $string

2 Comments

I had simplified it as it was redundant.
see the comments to the answer of @fedorqui

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.