PHP serialize() Function

PHP serialize() function is used for “converting a value (like an array, object, or even a simple data type) into a storable representation of its value”.

Syntax

serialize(value)

Parameters

 value(required): This is the value to be serialized.

Return value

It is a string that contains a byte-stream representation of value. The string can be stored anywhere.

Visual RepresentationVisual Representation of PHP serialize() Function

Example 1: How to Use serialize() function

<?php

$netflix = ['Black Mirror', 'Suits', 'Bird Box', 'Dirt'];

$serializeText = serialize($netflix);

echo $serializeText."\n";

Output

a:4:{i:0;s:12:"Black Mirror";i:1;s:5:"Suits";i:2;s:8:"Bird Box";i:3;s:4:"Dirt";}

Example 2: Serializing floating point

<?php

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

Output

98.19
d:98.19;
d:98.1921;

Why not use Serialize()

Avoid routinely serializing data and storing it in your database. Serialization should be used as a last resort, as it can complicate data handling. While serialize() can store complex data structures, this approach often bypasses the benefits of using the relational database model and the specific data types supported by your SQL database engine.

That’s it.

Leave a Comment

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