Serializing and unserializing variables in PHP

Josh Sherman
1 min read
Software Development 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:


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.

Join the Conversation

Good stuff? Want more?

Weekly emails about technology, development, and sometimes sauerkraut.

100% Fresh, Grade A Content, Never Spam.

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.

Currently Reading

Parasie Eve

Previous Reads

Buy Me a Coffee Become a Sponsor

Related Articles