Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert array into string in PHP

Tags:

arrays

php

i have an array like in PHP:

$a = array('110','111','121');

i want to convert it to :

$b = " '110' , '111' , '121' ";

is there any function in PHP that does it? i know it could be done with a loop on array and put value in $b, but i want a less more code solution.

thank you.

like image 729
hd. Avatar asked Dec 03 '22 08:12

hd.


2 Answers

You do need all those spaces and quotes? You can still use implode, although array_reduce might be nicer

$a = array(1, 2, 3, 4);

$x = "'".implode("' , '", $a)."'";

array_reduce:

$x = array_reduce($a, function($b, $c){return ($b===null?'':$b.' , ')."'".$c."'";});

Advantage of array_reduce, is that you will get NULL for an empty array, instead of ''. Note that you cannot use this inline function construct in php versions prior to 5.3. You'll need to make the callback a separate function and pass its name as a string to array_reduce.

like image 178
GolezTrol Avatar answered Dec 25 '22 06:12

GolezTrol


yes, check implode -- http://php.net/manual/en/function.implode.php

like image 45
sharoni Avatar answered Dec 25 '22 05:12

sharoni