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?
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?
Use '
before and after implode()
$temp = array("abc","xyz");
$result = "'" . implode ( "', '", $temp ) . "'";
echo $result; // 'abc', 'xyz'
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
You can set the glue to ', '
and then wrap the result in '
$res = "'" . implode ( "', '", $array ) . "'";
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.
$ids = array();
foreach ($file as $newaarr) {
array_push($ids, $newaarr['Identifiant']);
}
$ids =array_unique($ids);
//$idAll=implode(',',$ids);
$idAll = "'" . implode ( "', '", $ids ) . "'";
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'
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;
}
}