I am asked “How do I convert an array or object into a string” very frequently so I thought I would put a quick little tutorial together explaining the various different methods.
Converting an array OR object into a string(BEST METHOD)
We are going to use the functions serialize and unserialize.
These functions are very easy to use, for example converting an array or object you would do the following:
$string = serialize($objectorarray);
Now to convert the string back into an object or array we would do:
$objectorarray = unserialize($string);
It really is as simple as that, however sometimes the serialize function doesn’t do a good job at escaping characters so to get around this we do the following:
$string =base64_encode(serialize($objectorarray)); // This converts into a string$objectorarray = unserialize( base64_decode($string)); // This converts a string into an array or object
Converting an array into a string (OLD FASHIONED METHOD).
Implode and Explode can be used to convert an array.
Look at my example below.
$myarray[] = 'Apple';$myarray[] = 'Orange';
$string = implode('|',$myarray);
echo $string; // This would return Apple|Orange
Using the example above, the implode function takes two parameters. First our separator and second our array.
To now convert the string BACK into an array we use explode. See the example below.
$string = 'Apple|Orange';$myarray = explode('|',$string);
print_r($myarray);
The explode function takes pretty much the same parameters as implode except it looks for a string rather then an array.
Why would you want to convert an array or object into a string?
When saving vast amounts of data into a mysql table or even a text file, all you would need to do using the method above is save the string into the file or into a table row. Very useful if you have plenty of dynamic data… No need to create lots of column names when you can save the object or array into a single row!
#1 by Jack Thomspon on August 9th, 2009
Awesome tutorial!