Convert array to string in PHP

I have an array similar to PHP:

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

I want to convert it to:

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

is there any function in php? I know that this can be done with a loop in an array and put the value in $ b, but I want fewer solutions for the code.

thanks.

+4
source share
5 answers

Do you need all these 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."'";}); 

The advantage of array_reduce is that you get NULL for an empty array instead of '' . Please note: you cannot use this built-in function construct in php versions prior to 5.3. You will need to make the callback a separate function and pass your name as a string to array_reduce.

+8
source
+4
source

Well, this is a different approach.

 $arraystring = print_r($your_array, true); 

and if you want to print it elsewhere, then

 $arraystring = '<pre>'.print_r($your_array, true).'</pre>'; 

or you can mix many arrays and vars if you do

 ob_start(); print_r($var1); print_r($arr1); echo "blah blah"; print_r($var2); print_r($var1); $your_string_var = ob_get_clean(); 
+3
source

Use implode .

 $b = " '" . implode("' , '", $a) . "' "; 
+2
source

Very beautiful outp gives

 $arraystring = json_encode($your_array); 
0
source

All Articles