Serializing and unserializing variables in PHP

Serialization in PHP is the act of converting a variable into a storable value.
When I say storable, I mean being able to store the result in say, a database
or a flat file. This is commonly applied to arrays and objects as they are not
simply text strings. Under the hood, PHP uses serialize() for session data as
it is just an array. serialize() converts variables to storable strings:

$object = new AwesomeClass
$serial = serialize($object

$array  = [1, 2, 3, 4, 5
$serial = serialize($array

The second example, with the array would end up looking like this once it’s
been serialized:

a:5:{i:0i:1i:1i:2i:2i:3i:3i:4i:4i:5

You can see that the string is very much just a textual representation of the
array. It’s prefixed with a:5 which mean “this is an array with 5 elements”.
Then moving through the text inside the {}, you can see that it’s referencing
the index of the array followed by the value so i:0;i:1; can been seen as
“index 0 with a value of 1”.

Reversing the process is just as easy:

$array = unserialize($serial

In the instance that the passed variable is not unserializable, the function
will return boolean false and a PHP notice is raised.

Josh Sherman - The Man, The Myth, The Avatar

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.


If you found this article helpful, please consider buying me a coffee.