How to Use serialize() and unserialize() in PHP

In PHP, there is no possibility of transporting or storing data. For executing a complex set of data continuously, the serialize() and unserialize() functions come in rescue. They are especially handy for dealing with complex data.

Most of the time, developers need to store a complex array inside a file or a database. The complex arrays are those with elements of more than a single data type or array.

In this tutorial, we will show you how to use the serialize() and unserialize() functions to accomplish your goals.

Watch a course Learn object oriented PHP

Using the serialize() Function

It is an inbuilt PHP function that is used for serializing a particular array.

It accepts only one parameter that is the data one intends to serialize. The serialize() function is capable of returning a serialized string.

The syntax of the serialize() function is:

serialize( $values_in_form_of_array ): string

Below, you can see an accurate example of using this function:

<?php

// Complex array
$myvar = ['hello', 36, [1, 'two'], 'apple'];

// Convert to a string
$string = serialize($myvar);

// Printing the serialized data
echo $string;

?>

The output of the example is as follows:

 a:4:{i:0;s:5:"hello";i:1;i:36;i:2;a:2:{i:0;i:1;i:1;s:3:"two";}i:3;s:5:"apple";}

The unserialize() Function

The unserialize() function is another inbuilt PHP function. It is used for unserializing a particular serialized array to return to the initial value of the complex array $myvar.

The syntax of this function will look as follows:

unserialize(string $data, array $options = []): mixed

Now, let’s see how both serialize() and unserialize() are used in practice:

<?php 
$myvar = ['hello',  42, [1, 'two'], 'apple'];

// Serialize the above data 
$string = serialize($myvar);

// Unserialize the data in $string 
$newvar = unserialize($string);

// Print the unserialized data 
print_r($newvar);

?>

The output of the example is as follows:

  [
    [0] => hello
    [1] => 42
    [2] => 
        [
            [0] => 1
            [1] => two
        ]
    [3] => apple
  ]

For more information and usage examples of these functions, you can check out PHP serialize() and PHP unserialize().

There is a powerful symfony Serializer component which extends serialization possibilities.