How to Serialize Function in PHP

Sheeraz Gul Feb 02, 2024
  1. Demonstrate the Use of serialize() and unserialize() on One Dimensional Array in PHP
  2. Demonstrate the Use of Serialize() and Unserialize() on Multi Dimensional Array in PHP
  3. Difference Between Serialize() and json_encode() in PHP
How to Serialize Function in PHP

PHP serialize() is used to convert the complex data structure into the format of the particular string so we can use them outside a running PHP script.

Simply the serialize() is used to put the data structure into a lower common denominator to use them in text files, sockets, or databases.

This tutorial demonstrates the use of serialize() and unserialize().

Demonstrate the Use of serialize() and unserialize() on One Dimensional Array in PHP

PHP serialize() takes one only parameter, which is the value you want to serialize, the same is for the unserialize(). See example:

<?php
$demo_array = array("delftstack1", "delftstack3", "delftstack3");
//serialize one dimensional array
$serialized_data = serialize($demo_array);
echo $serialized_data."<br>";
//Userialize the serialized array
$Unserialized_data = unserialize($serialized_data);
print_r($Unserialized_data);
echo "<br><br>";

//serialize an assosiative array
$demo_array= array( 'Val1' => 'delftstack1', 'Val2'=> 'delftstack3', 'Val3'=>'delftstack3');
$serialized_data = serialize($demo_array);
echo $serialized_data."<br>";
//Userialize the serialized array
$Unserialized_data = unserialize($serialized_data);
print_r($Unserialized_data);
?>

PHP serialize() a simple array and an associative array, then reverse the operation by unserialize().

Output:

a:3:{i:0;s:11:"delftstack1";i:1;s:11:"delftstack3";i:2;s:11:"delftstack3";}
Array ( [0] => delftstack1 [1] => delftstack3 [2] => delftstack3 )

a:3:{s:4:"Val1";s:11:"delftstack1";s:4:"Val2";s:11:"delftstack3";s:4:"Val3";s:11:"delftstack3";}
Array ( [Val1] => delftstack1 [Val2] => delftstack3 [Val3] => delftstack3 )

The serialize generates a string with all the data of a given array. The serialized string, a=size of the array, i=count of array number, and s=size of array values.

The output shows that if the array is not associative, the serialize will still generate the output in terms of an associative array.

Demonstrate the Use of Serialize() and Unserialize() on Multi Dimensional Array in PHP

For the multi-dimensional array, the output will be similar.

<?php
$multidimentional_array= array(
    array(
        array("delftstack1", 10, 15.5),
        array("delftstack2", 15, 25.5)
       ),
    array(
        array("delftstack1", 15, 25.5),
        array("delftstack2", 20, 30.5)
       ),
    array(
        array("delftstack1", 20, 30.5),
        array("delftstack2", 30, 35.5) 
    )
);
//serialize one dimensional array
$serialized_data = serialize($multidimentional_array);
echo $serialized_data."<br><br><br>";
//Userialize the serialized array
$Unserialized_data = unserialize($serialized_data);
print_r($Unserialized_data);
?>

Output:

a:3:{i:0;a:2:{i:0;a:3:{i:0;s:11:"delftstack1";i:1;i:10;i:2;d:15.5;}i:1;a:3:{i:0;s:11:"delftstack2";i:1;i:15;i:2;d:25.5;}}i:1;a:2:{i:0;a:3:{i:0;s:11:"delftstack1";i:1;i:15;i:2;d:25.5;}i:1;a:3:{i:0;s:11:"delftstack2";i:1;i:20;i:2;d:30.5;}}i:2;a:2:{i:0;a:3:{i:0;s:11:"delftstack1";i:1;i:20;i:2;d:30.5;}i:1;a:3:{i:0;s:11:"delftstack2";i:1;i:30;i:2;d:35.5;}}}


Array ( [0] => Array ( [0] => Array ( [0] => delftstack1 [1] => 10 [2] => 15.5 ) [1] => Array ( [0] => delftstack2 [1] => 15 [2] => 25.5 ) ) [1] => Array ( [0] => Array ( [0] => delftstack1 [1] => 15 [2] => 25.5 ) [1] => Array ( [0] => delftstack2 [1] => 20 [2] => 30.5 ) ) [2] => Array ( [0] => Array ( [0] => delftstack1 [1] => 20 [2] => 30.5 ) [1] => Array ( [0] => delftstack2 [1] => 30 [2] => 35.5 ) ) )

Difference Between Serialize() and json_encode() in PHP

The json_encode() is another built-in method in PHP that converts an array or an object to a string, it uses JSON to perform the operation, and similarly, for unserialize(), json_decode() can be used.

There are a few differences between serialize() and json_encode().

  • Serialize() is usually faster than json_encode().
  • JSON is more portable.
  • For UTF-8 characters you don’t need to do anything in serialize(), but with json_encode() you need to put an extra parameter JSON_UNESCAPED_UNICODE. Otherwise, the JSON converts the UTF-8 to Unicode escape sequences.
  • serialize() have a memory of the object’s original class while JSON doesn’t; they store the data as instances of stdClass.

Lets compare serialize() and json_encode():

<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

$demo_array= array( 'Val1' => 'delftstack1', 'Val2'=> 'delftstack3', 'Val3'=>'delftstack3');

// `json_encode()` time
$start_time = microtime(true);
json_encode($demo_array);
$json_time = microtime(true) - $start_time;
echo "`json_encode()` encoded the array in $json_time seconds<br>";

// `serialize()` time
$start_time = microtime(true);
serialize($demo_array);
$serialize_time = microtime(true) - $start_time;
echo "`serialize()` serialized the array in $serialize_time seconds<br>";

// Comparing `json_encode()` and `serialize()`
if ($json_time < $serialize_time) {
    printf("json_encode() is %01.2f%% faster than serialize() for this array<br>", ($serialize_time / $json_time - 1) * 100);
}
else if ($serialize_time < $json_time ) {
    printf("serialize() is %01.2f%% faster than json_encode() for this array<br>", ($json_time / $serialize_time - 1) * 100);
} else {
    echo "Cannot Compare!<br>";
}
?>

Output:

`json_encode()` encoded the array in 4.0531158447266E-6 seconds
`serialize()` serialized the array in 2.1457672119141E-6 seconds
serialize() is 88.89% faster than json_encode() for this array

As we can see the serialize() is 88.89% faster than json_encode for the given array.

Usually serialize() is the faster one but sometimes json_encode() can operate faster but the margin is very low.

Author: Sheeraz Gul
Sheeraz Gul avatar Sheeraz Gul avatar

Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.

LinkedIn Facebook