How to convert array to a string using methods other than JSON?
serialize()
is the function you are looking for. It will return a string representation of its input array or object in a PHP-specific internal format. The string may be converted back to its original form with unserialize()
.
But beware, that not all objects are serializable, or some may be only partially serializable and unable to be completely restored with unserialize()
.
$array = array(1,2,3,'foo');
echo serialize($array);
// Prints
a:4:{i:0;i:1;i:1;i:2;i:2;i:3;i:3;s:3:"foo";}
Use the implode()
function:
$array = array('lastname', 'email', 'phone');
$comma_separated = implode(",", $array);
echo $comma_separated; // lastname,email,phone
readable output!
echo json_encode($array); //outputs---> "name1":"value1", "name2":"value2", ...
OR
echo print_r($array, true);
You are looking for serialize(). Here is an example:
$array = array('foo', 'bar');
//Array to String
$string = serialize($array);
//String to array
$array = unserialize($string);