PHP add single quotes to comma separated list

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


Use ' before and after implode()

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

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

echo $result; // 'abc', 'xyz'

It can also be as short as this:

sprintf("'%s'", implode("', '", $array))

Tags:

Php

Arrays

String