AppDividend
Latest Code Tutorials

PHP Serialize Example | Serialize() Function Tutorial

0

PHP Serialize Example | Serialize() Function Tutorial is today’s topic. The serialize() function in PHP converts a storable representation of the value. The serialize 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. It is useful for storing or passing PHP values around without losing their type and structure.

PHP Serialize Example

The syntax of serialize() function is following.

serialize(value)

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

Let’s see the following example.

<?php

// app.php

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

The output is following.

 

PHP Serialize Example

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

Here, one thing to note 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 a weird precision offset errors.

<?php

// app.php

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

The output is following.

 

Serializing floating point

Why not use Serialize()

DO NOT the 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 to other languages, like let’s say you find that 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 say one module, but you do not want to serialize the data each time.

Finally, PHP Serialize Example | Serialize() Function Tutorial is over.

Leave A Reply

Your email address will not be published.

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