139

Possible Duplicate:
How to create comma separated list from array in PHP?

My array looks like this:

Array
(
    [0] => lorem
    [1] => ipsum
    [2] => dolor
    [3] => sit
    [4] => amet
)

How to transform this to a string like this with php?

$string = 'lorem, ipsum, dolor, sit, amet';
Community
  • 1
  • 1
m3tsys
  • 3,939
  • 6
  • 31
  • 45

4 Answers4

299
$arr = array ( 0 => "lorem", 1 => "ipsum", 2 => "dolor");

$str = implode (", ", $arr);
Josh
  • 8,082
  • 5
  • 43
  • 41
omabena
  • 3,561
  • 1
  • 17
  • 13
21

Directly from the docs:

$comma_separated = implode(",", $array);
Nobita
  • 23,519
  • 11
  • 58
  • 87
  • 3
    I used implode with a little modification. Since I needed a comma-separated list with single quotes as well, I used the following on my array: $innie = implode("', '", $arrayDistricts); [Note the single quotes inside the double quotes.] Then I used this in my query: IN ('$innie') [Note the single quotes around the variable.] – KiloVoltaire Aug 09 '15 at 03:27
  • Thanks Kilo thats exactly what i was looking for. I am using it in a bulk update – Sweet Chilly Philly Feb 08 '19 at 02:22
18

Make your array a variable and use implode.

$array = array('lastname', 'email', 'phone');
$comma_separated = implode(",", $array);

echo $comma_separated; // lastname,email,phone

http://php.net/manual/en/function.implode.php

Josh
  • 8,082
  • 5
  • 43
  • 41
Adam
  • 3,615
  • 6
  • 32
  • 51
10

You're looking for implode()

$string = implode(",", $array);

JKirchartz
  • 17,612
  • 7
  • 60
  • 88