40

When I implode my array I get a list that looks like this:

qwerty, QTPQ, FRQO

I need to add single quotes so it looks like:

'qwerty', 'QTPQ', 'FRQO'

Can this be done using PHP?

Rizier123
  • 58,877
  • 16
  • 101
  • 156
Tom Canfarotta
  • 743
  • 1
  • 5
  • 14

8 Answers8

104

Use ' before and after implode()

$temp = array("abc","xyz");

$result = "'" . implode ( "', '", $temp ) . "'";

echo $result; // 'abc', 'xyz'
Ypages Onine
  • 1,262
  • 1
  • 8
  • 8
20

Here is another way:

$arr = ['qwerty', 'QTPQ', 'FRQO'];

$str = implode(', ', array_map(function($val){return sprintf("'%s'", $val);}, $arr));

echo $str; //'qwerty', 'QTPQ', 'FRQO'

sprintf() is a clean way of wrapping the single quotes around each item in the array

array_map() executes this for each array item and returns the updated array

implode() then turns the updated array with into a string using a comma as glue

Klompenrunner
  • 723
  • 7
  • 13
9

It can also be as short as this:

sprintf("'%s'", implode("', '", $array))
Gale Yao
  • 133
  • 1
  • 10
5

You can set the glue to ', ' and then wrap the result in '

$res = "'" . implode ( "', '", $array ) . "'";

http://codepad.org/bkTHfkfx

Musa
  • 96,336
  • 17
  • 118
  • 137
1

Similar to what Rizier123 said, PHP's implode method takes two arguments; the "glue" string and the "pieces" array.

so,

$str = implode(", ", $arr);

gives you the elements separated by a comma and a space, so

$str = implode("', '", $arr);

gives you the elements separated by ', '.

From there all you need to do is concatenate your list with single quotes on either end.

jc_programmer
  • 27
  • 1
  • 7
1
    $ids = array();
    foreach ($file as $newaarr) {
        array_push($ids, $newaarr['Identifiant']);

    }
   $ids =array_unique($ids);
    //$idAll=implode(',',$ids);

     $idAll = "'" . implode ( "', '", $ids ) . "'";
Ashish Pathak
  • 827
  • 8
  • 16
1

You can use the method called 'implode' in the PHP. That will help you to concatenate all the array values with th given delimiter.

$arr = ['qwe', 'asd', 'zxc'];
echo implode(',', array_map(function($i){return "'".$i."'";}, $arr));

You output will be something like below:

'qwe','asd','zxc'
Punit Gajjar
  • 4,937
  • 7
  • 35
  • 70
1rx
  • 43
  • 1
  • 5
0
function implode_string($data, $str_starter = "'", $str_ender = "'", $str_seperator = ",") {
    if (isset($data) && $data) {
        if (is_array($data)) {
            foreach ($data as $value) {
                $str[] = $str_starter . addslashes($value) . $str_ender . $str_seperator;
            }
            return (isset($str) && $str) ? implode($str_seperator, $str) :  null;
        }
        return $str_starter . $data . $str_ender;
    }
}
Gullu Mutullu
  • 427
  • 4
  • 3