W3docs

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

This tutorial can be quite helpful for you, if you are interested in using the PHP serialize() and unserialized() functions in your programming practice.

In PHP, complex data structures like arrays and objects cannot be directly stored in files or databases as plain text. To transport or store them, the <kbd class="highlighted">serialize()</kbd> and <kbd class="highlighted">unserialize()</kbd> functions come in handy. They are especially useful for handling 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 <kbd class="highlighted">serialize()</kbd> and <kbd class="highlighted">unserialize()</kbd> functions to accomplish your goals.

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 <kbd class="highlighted">serialize()</kbd> function is capable of returning a serialized string.

The syntax of the <kbd class="highlighted">serialize()</kbd> function is:

php serialize() syntax

serialize( $values_in_form_of_array ): string

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

php serialize() 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:

php unserialize()

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

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

php serialize(), php unserialize()

<?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
  ]
Warning

Never use unserialize() <kbd class="highlighted"> json_encode() </kbd> json_decode() instead.

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

Info

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