Dumbo
Dumbo

Reputation: 14142

Converting a nummeric array to comma separated string

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?

Upvotes: 0

Views: 60

Answers (4)

Expedito
Expedito

Reputation: 7805

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, ',');

Upvotes: 2

jbx
jbx

Reputation: 22178

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()

Upvotes: 1

exussum
exussum

Reputation: 18578

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)

Upvotes: 1

Bart Friederichs
Bart Friederichs

Reputation: 33573

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.

Upvotes: 1

Related Questions