If you have an object or array that you want to save until a later you can use the serialize() and unserialize() functions. The operation of the functions are straightforward. To serialize() an array just pass the serialise function the array like this.
$array = array(1,2,3,4); $serializedArray = serialize($array);
Now when we print the serialized array out we get the following.
This contains all of the data needed to recreate our array. Be careful not to edit this string because it will not work if you want to unserialize it and get the array back. You can store this string in a file or a database so that you can recreate the exact same array at a later date.
If you do chose to store the serialized string in a database you might want to encode it as well. This is to stop the database encoding or removing any characters and destroying your array. To encode the string you can use the base64_encode function in this way.
$encodedSerializedArray = base64_encode(serialize($array));
This string now contains the following.
To get the array back again we use the unserialize() function like this. If you used the base64_encode() to encode the array then you can use the base64_decode() function to turn it back into an unserializable string again.
$array = unserialize($array);
The $array variable now contains our original array.
The same can also be done with objects in exactly the same way. The main difference is that PHP will try to call the __wakeup() function of the object (if it exists) once it has been reconstructed.