PHP Serialize: The Complete Guide

The serialize() function is useful for storing or passing PHP values around without losing their type and structure.

PHP serialize

PHP serialize() is a built-in function that converts a storable representation of the value. The serialized data means the sequence of bits so that it can be stored in the file, a memory buffer, or transmitted across the network connection link.


The syntax of serialize() function is following.



The value parameter is required, which is the value to be serialized.


Let’s see the following example.


// app.php

$netflix = ['Black Mirror', '13 Reasons Why', 'Bird Box', 'Dirt'];
$serializeText = serialize($netflix);
echo $serializeText."\n";

See the output.

PHP Serialize Example

The serialized text looks like the above image. That text can now be stored in the database, and when we need to display the data to the frontend, we can deserialize() the data and get back to the original format.

One thing to note is that many built-in PHP objects cannot be serialized.

When serialize() serializes objects, a leading backslash is not included in a class name of namespaced classes for maximum compatibility.

Serializing floating point

Serializing floating-point numbers leads to weird precision offset errors.


// app.php

echo round(98.19210000000000002, 2)."\n";
echo serialize(round(98.19210000000000002, 2))."\n";
echo serialize(98.1921)."\n";

See the output.

Serializing floating point

Why not use Serialize()

DO NOT serialize data and place it into your database every time.

Use it when you do not have any other choice left. It can be complicated sometimes. Serialize can be used to store the data, but that’s missing the point of the relational database and the SQL datatypes inherent in your database engine.

Doing this makes the data in your database non-portable, difficult to read, and can lead to complicating the queries.

If you want your application to be used by other languages, like let’s say you want to use Python or Java for some portion of your app that it makes sense to use Python or Java in, serialization will become painful.

You should always be able to query any data and modify data in a database without using the third-party intermediary tool to manipulate data to be inserted.

So, every time, serialize() may not be a great option. It can be used to, let’s say, one module, but you do not want to serialize the data each time.

That’s it for this tutorial.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.