0

I have an array like this:

[participants] => Array
    (
        [0] => 9
        [1] => 8
        [2] => 12
    )

I want to put it in another variable to look like this:

"9,8,12"

I tried with the code below but it does not output anything:

$mem = "";
for($i = 0; $i < count($participants); $i++)
{
    $mem.$participants[$i];
}

echo $mem;

What can be the problem?

2
  • You are not putting any commas in between your numbers, you would need to change this line: $mem.$participants[$i];, but why bother when you can use implode(). Commented Aug 7, 2013 at 21:50
  • if you want to concatenate them and put them into $mem you have to do the = sign first. So $mem .= $participants[$i];. To put comas in between you can do $mem .= ($i > 0) ? ','.$participants[$i] : $participants[$i]; but you can use the implode() function to do this for you as the others indicated. Commented Aug 7, 2013 at 21:53

4 Answers 4

2

The easiest way would be to use implode:

implode(',', $participants);

In your code you should have used concatenation like this:

$mem .= $participants[$i].',';

However, I would have preferred foreach like this:

$mem = "";
foreach ($participants as $key => $value){
    $mem .= $value.',';
}

If you're looping in that way, you have to get rid of the last comma when you're done:

$mem = rtrim($mem, ',');
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks :P that did the trick, but can you also tell me what is wrong with my own code?
1

Use PHP's implode function:

$s = implode(",", $participants);

The reason that your code doesn't work, is because you never do anything to $mem. To append strings to a string, use the .= operator:

$mem .= $participants[$i];

You'll see it will just glue everything together, without commas.

Comments

1

to fix your code. your not assigning the result to anything

$mem = $mem. "," .$participants[$i];

or

$mem .=  "," . $participants[$i];

but implode is a better solution

also your looping method would require you to remove the comma at the start (or end)

Comments

1

Your code should be:

$mem = "";
for($i = 0; $i < count($participants); $i++)
{
   $mem .= ($i > 0) ? ",".$participants[$i] : $participants[$i];
}

echo $mem;

but as the others said, use PHP implode()

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.