php implode with quotes
Asked Answered
H

17

158

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 ?

Hunley answered 23/5, 2011 at 20:6 Comment(4)
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.Barmaid
The only drawback is it will produce one empty string if the array is empty. ie. equivalent to $comma_separated = "''";Vitalism
Topically related: Enclosing every field with double quotes in CSV file using PHP? and Forcing fputcsv to Use Enclosure For all Fields and Alternative to fputcsvIntermixture
If this question is being asked as a means to prepare strings for a SQL query, then this is an XY Problem. Passing an array of values into, say, an IN expression should be done via a prepared statement -- and here is that canonical: How can I bind an array of strings with a mysqli prepared statement?. This question's minimal reproducible example does not include the challenge of dealing with strings which already contain single quotes -- certainly something to be concerned with to avoid bugs.Intermixture
P
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).

Pelecypod answered 23/5, 2011 at 20:10 Comment(1)
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 helpHunley
S
209
$array = array('lastname', 'email', 'phone');


echo "'" . implode("','", $array) . "'";
Sherbrooke answered 6/4, 2012 at 13:25 Comment(2)
Watch out for empty array while using this solution.Penza
Thanks. I used this for <ul> <li> {!! implode('</li><li>', session('messages')) !!} </li> </ul>Celie
H
51
$ids = sprintf("'%s'", implode("','", $ids ) );
Hyperesthesia answered 12/12, 2016 at 19:26 Comment(0)
K
48

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.

Keely answered 23/5, 2011 at 20:12 Comment(11)
@Felix Kling I suspect this would be slower as well ?Hunley
@mcgrailm, i ask again: slower than what?Hocker
@mcgrailm: Maybe, I suggest you make a benchmark and find out ;)Keely
@Felix Kling how do I do that ?Hunley
@Hunley put various echoes of time() and subtract them (at the start and end of your code)Hocker
This has the added benefit of allowing you to escape any single quotes which may appear in the array elementsBarmaid
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 php.net/manual/es/function.str-pad.phpBarthold
one liner: implode(',', array_map(fn($str) => "\"{$str}\"", $array));Cuddy
one liner version $csv = implode(',', array_map(function($str){ return sprintf("'%s'", $str); }, $array));Turbinate
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?Marplot
2011 post, still valid. Now it's possible to use arrow functions: $csv=implode(',', array_map(fn($s)=>sprintf("'%s'", $s), $array));Backplate
P
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).

Pelecypod answered 23/5, 2011 at 20:10 Comment(1)
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 helpHunley
T
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)."'";
Teocalli answered 1/2, 2013 at 4:36 Comment(1)
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 finiteHunley
H
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

Hocker answered 23/5, 2011 at 20:12 Comment(5)
@mcgrailm, slower than what? Its basically the same thing as an array_map but without using array_mapHocker
slower than the way I currently create my csv stringHunley
@Hunley see @FelixKling's commentHocker
+1 seem the only one correct answer - all other answers will produce empty string when trying to implode empty array. This one wont.Telford
Thanks @DenisMatafonov :-)Hocker
S
7
$id = array(2222,3333,4444,5555,6666);
$ids = "'".implode("','",$id)."'";

Or

$ids = sprintf("'%s'", implode("','", $id ) );
Superpower answered 6/12, 2020 at 5:37 Comment(0)
W
2

Alternatively you can create such a function:

function implode_with_quotes(array $data)
{
    return sprintf("'%s'", implode("', '", $data));
}
Wimsatt answered 23/8, 2016 at 6:29 Comment(0)
Y
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.

Yclept answered 29/5, 2021 at 4:12 Comment(0)
A
2

try this code :

$data = 'ABC,DEF,GHI';

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


echo $str;
Azeotrope answered 1/10, 2021 at 10:16 Comment(0)
G
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.

Godinez answered 27/6, 2016 at 23:59 Comment(0)
M
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.

Melli answered 12/6, 2018 at 12:55 Comment(1)
Good solution. And Can have ltrim and rtim to remove square brackets [ and ].Subaqueous
C
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.

Cadenza answered 1/12, 2020 at 13:37 Comment(0)
A
0

you can do it this way also

<?php
$csv= '\'' . join(array('lastname', 'email', 'phone'),'\',').'\'';
echo $csv;
?>
Americium answered 23/5, 2011 at 20:16 Comment(1)
join is just an alias of implodeHunley
D
0

I think this is what you are trying to do

$array = array('lastname', 'email', 'phone');
echo "'" . implode("','", explode(',', $array)) . "'";
Downs answered 3/9, 2014 at 13:33 Comment(0)
C
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?

Catania answered 26/5, 2023 at 11:3 Comment(0)
I
0

Unconditionally wrapping the imploded string with quotes will result in an empty quoted string when the array is empty -- this doesn't feel ideal because it gives the same result as an array with a lone element containing empty string (an ambiguous result).

Instead, just use preg_replace() to target the start and end positions of each string and inject a quote on those positions.

Code: (Demo)

$array = ['lastname', 'email', 'phone'];

echo implode(",", preg_replace('/^|$/', "'", $array));

This doesn't deal with the possibility of escaping single quotes that already exist in the values. If you want to escape in-value single quotes with backslashes, you can make iterated calls of addcslashes() with single quotes nominated for escaping and manually concatenate the outer single quotes. Don't worry about speed as a top priority -- making your application bug-free is the first concern. (Demo)

echo implode(",", array_map(fn($v) => "'" . addcslashes($v, "'") . "'", $array));
Intermixture answered 22/2 at 23:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.