Skip to content

What is data serialization?

First of all, I couldn’t get clear definition of it from WikiPedia or even from serialize function in the PHP manual. I need to know some cases where we need the term serialization and how things are going without it? In other words, Where you need serialization and without it your code will be missing some important feature.


What is serialization?

Serialization encodes objects into another format.
For example you have an array in PHP like this:

$array = array("a" => 1, "b" => 2, "c" => array("a" => 1, "b" => 2));

And then you want to store it in file or send to other application.

There are several format choices, but the idea is the same: The array has to be encoded (or you could say “translated”), into text or bytes, that can be written to a file or sent via the network.
For example, in PHP, if you:

$data = serialize($array);

you will get this:


This is PHP’s particular serializing format that PHP understands, and it works vice versa, so you are able to use it to deserialize objects.
For example, you stored a serialized array in a file, and you want it back in your code as an array:

$array = unserialize($data);

But you could choose a different serialization format, for example, JSON:

$json = json_encode($array);

will give you this:


The result is not only easily saved, read by human eye, or sent via network, but is also understandable by almost every other language (JavaScript, Java, C#, C++, …)

Serialization translate objects to another format, in case you want to store or share data.

Are there any situations, where you cannot do anything, but serialize it?

No. But serialization usually makes things easier.

Are JSON and PHP format the only possible formats?
No, no, no and one more time no. There are plenty of formats.

  • XML (e.g. using a schema like WSDL or XHTML)
  • Bytes, Protobuf, etc.
  • Yaml
  • Your own formats (you can create your own format for serialization and use it, but that is a big thing to do and is not worth it, most of the time)