154

Imploding a simple array

would look like this

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

and that would return this

 lastname,email,phone

great, so i might do this instead

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

and now i have what I want a nice pretty csv string

 'lastname','email','phone'

is there a better way to do this, it feels to me like there should be an optional parameter for implode am I missing something ?

mcgrailm
  • 17,469
  • 22
  • 83
  • 129
  • 13
    I see a lot of comments about the provided answers being "slower". **It does not matter**. Choose the way which is clearer and more maintainable, worry about performance later, if at all. – user229044 May 24 '11 at 18:18
  • 3
    The only drawback is it will produce one empty string if the array is empty. ie. equivalent to `$comma_separated = "''";` – scipilot Nov 12 '14 at 03:25

16 Answers16

201
$array = array('lastname', 'email', 'phone');


echo "'" . implode("','", $array) . "'";
Umesh Moghariya
  • 3,063
  • 6
  • 21
  • 23
49
$ids = sprintf("'%s'", implode("','", $ids ) );
Robb
  • 611
  • 5
  • 2
47

You could use array_map():

function add_quotes($str) {
    return sprintf("'%s'", $str);
}

$csv =  implode(',', array_map('add_quotes', $array));

DEMO

Also note that there is fputcsv if you want to write to a file.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • @Felix Kling I suspect this would be slower as well ? – mcgrailm May 23 '11 at 20:20
  • 1
    @mcgrailm, i ask again: slower than what? – Naftali May 23 '11 at 20:21
  • 3
    @mcgrailm: Maybe, I suggest you make a benchmark and find out ;) – Felix Kling May 23 '11 at 20:23
  • @Felix Kling how do I do that ? – mcgrailm May 23 '11 at 20:24
  • @mcgrailm put various echoes of `time()` and subtract them (at the start and end of your code) – Naftali May 23 '11 at 20:28
  • 1
    This has the added benefit of allowing you to escape any single quotes which may appear in the array elements – user229044 May 24 '11 at 18:17
  • str_pad is faster as i know. `$result = implode(', ', array_map(function ($e) {return str_pad($e, strlen($e) + 2, '\'', STR_PAD_BOTH);}, $str))` see http://php.net/manual/es/function.str-pad.php – UselesssCat Mar 14 '19 at 19:08
  • one liner: `implode(',', array_map(fn($str) => "\"{$str}\"", $array));` – dave Feb 26 '22 at 01:24
  • one liner version `$csv = implode(',', array_map(function($str){ return sprintf("'%s'", $str); }, $array));` – Stefano Mtangoo Nov 09 '22 at 10:48
  • This seems to work well but, as with my own attempt `"'" . str_replace(",", "','", rtrim(implode(',', $values), ',')) . "'"` , it also quotes integers which might not always be desirable unless you need string-integers for some reason. How can those be filtered out to not be quoted? – DonP May 28 '23 at 03:23
  • 2011 post, still valid. Now it's possible to use arrow functions: $csv=implode(',', array_map(fn($s)=>sprintf("'%s'", $s), $array)); – dAm2K Jul 07 '23 at 12:15
30

No, the way that you're doing it is just fine. implode() only takes 1-2 parameters (if you just supply an array, it joins the pieces by an empty string).

Rafe Kettler
  • 75,757
  • 21
  • 156
  • 151
  • its seems there is no speed difference in any of these solutions I'll just keep doing it they way I always have, thanks for everyones help – mcgrailm May 23 '11 at 20:48
24

Don't know if it's quicker, but, you could save a line of code with your method:

From

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

To:

$array = array('lastname', 'email', 'phone');
$comma_separated = "'".implode("','", $array)."'";
  • 2
    and i could further that but putting the definition of array in where the variable $array is in the last line but I the speed diff would be so finite – mcgrailm Feb 01 '13 at 06:05
10

If you want to use loops you can also do:

$array = array('lastname', 'email', 'phone');
foreach($array as &$value){
   $value = "'$value'";
}
$comma_separated = implode(",", $array);

Demo: http://codepad.org/O2kB4fRo

Naftali
  • 144,921
  • 39
  • 244
  • 303
7
$id = array(2222,3333,4444,5555,6666);
$ids = "'".implode("','",$id)."'";

Or

$ids = sprintf("'%s'", implode("','", $id ) );
Mobarak Hossen
  • 767
  • 5
  • 7
2

Alternatively you can create such a function:

function implode_with_quotes(array $data)
{
    return sprintf("'%s'", implode("', '", $data));
}
2

Another solution is achieved using implode + preg_replace as follows:

$a = ['A', 'B', 'C'];
implode(',', preg_replace('/^(.*)$/', '"$1"', $a)); // "A","B","C"
$b = [];
implode(',', preg_replace('/^(.*)$/', '"$1"', $b)); // empty string

As you can see this also saves you from checking if the array is empty.

2

try this code :

$data = 'ABC,DEF,GHI';

$str = "'".str_replace(',',"','",$data)."'";


echo $str;
1

If you want to avoid the fopen/fputcsv sub-systems here's a snippet that builds an escaped CSV string from an associative array....

$output = '';
foreach ($list as $row) {
  $output .= '"' . implode('", "', array_values($row)) . '"' . "\r\n";
}

Or from a list of objects...

foreach ($list as $obj) {
  $output .= '"' . implode('", "', array_values((array) $obj)) . '"' . "\r\n";
}

Then you can output the string as desired.

doublejosh
  • 5,548
  • 4
  • 39
  • 45
1

Another possible option, depending on what you need the array for:

$array = array('lastname', 'email', 'phone');
echo json_encode($array);

This will put '[' and ']' around the string, which you may or may not want.

Jeremy French
  • 11,707
  • 6
  • 46
  • 71
1

Don't forget to escape your data! If you want to put data in a CSV file without fputcsv function or put it in a SQL query use this code:

$comma_separated = "'" . implode("','", array_map('addslashes', $array)) . "'";

This code avoids SQL injection or data fragmentation when input array contains single quotation or backslash characters.

Mahoor13
  • 5,297
  • 5
  • 23
  • 24
0

I think this is what you are trying to do

$array = array('lastname', 'email', 'phone');
echo "'" . implode("','", explode(',', $array)) . "'";
rack_nilesh
  • 553
  • 5
  • 18
0

you can do it this way also

<?php
$csv= '\'' . join(array('lastname', 'email', 'phone'),'\',').'\'';
echo $csv;
?>
Senad Meškin
  • 13,597
  • 4
  • 37
  • 55
0

I know this is an oldi but I just created this snippet

public static function quoted_implode($array = null, $sep = ','){
        $keys = null;
        if(null !== $array && is_array($array)){
            $keys = implode('"'. $sep .'"',$array);
            $keys =  '"'.$keys .'"';
        }
        return $keys;
}

I wrote it as a method but easy to transform to a plain function.

How to use (this is just a line of another method I working on)?

$js_output .= "\t".'input_ids:['.self::quoted_implode($options['input_ids']).'],'.PHP_EOL;

Results in:(js) input_ids:["test_number","test_input1","test_input2"],

Might help someone?

Aad Pouw
  • 1
  • 2