The Wayback Machine - https://web.archive.org/web/20240707003236/https://www.geeksforgeeks.org/php-serializing-data/
Open In App

PHP | Serializing Data

Last Updated : 23 Aug, 2019
Improve
Improve
Like Article
Like
Save
Share
Report

Most often we need to store a complex array in the database or in a file from PHP. Some of us might have surely searched for some built-in function to accomplish this task. Complex arrays are arrays with elements of more than one data-types or array.
But, we already have a handy solution to handle this situation. We don’t have to write our own function to convert the complex array to a formatted string. There are two popular methods of serializing variables.

  • serialize()
  • unserialize()

We can serialize any data in PHP using the serialize() function. The serialize() function accepts a single parameter which is the data we want to serialize and returns a serialized string. Below program illustrate this:




<?php
  
// a complex array
$myvar = array(
    'hello',
    42,
    array(1, 'two'),
    'apple'
);
  
// convert to a string
$string = serialize($myvar);
  
// printing the serialized data
echo $string;
  
?>


Output:

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

From the above code, we have a variable with serialized data, $string . We can unserialize the value of the variable using unserialize() function to get back to the original value of the complex array, $myvar.

Below program illustrate both serialize() and unserialize() functions:




<?php
  
// a complex array
$myvar = array(
    'hello',
    42,
    array(1, 'two'),
    'apple'
);
  
// serialize the above data
$string = serialize($myvar);
  
// unserializing the data in $string
$newvar = unserialize($string);  
   
// printing the unserialized data 
print_r($newvar);
  
?>


Output:

Array
(
    [0] => hello
    [1] => 42
    [2] => Array
        (
            [0] => 1
            [1] => two
        )

    [3] => apple
)

This was the native PHP serialization method. However, since JSON has become so popular in recent years, they decided to add support for it in PHP 5.2. Now you can use the json_encode() and json_decode() functions as well for serializing and unserializing data in PHP respectively.

Since the JSON format is text only, it can be easily sent to and from a server and can be used as a data format by any programming language.

Lets have a look how to use json_encode() in PHP:




<?php
  
// a complex array
$myvar = array(
    'hello',
    42,
    array(1, 'two'),
    'apple'
);
  
// serializing data
$string = json_encode($myvar);
  
// printing the serialized data
echo $string;
  
?>


Output:

["hello",42,[1,"two"],"apple"]

We can decode the data encoded in above program using the json_decode() function to get the original complex array. Below program illustrate this:




<?php
  
// a complex array
$myvar = array(
    'hello',
    42,
    array(1, 'two'),
    'apple'
);
  
// serializing data
$string = json_encode($myvar);
  
// decoding the above encoded string
$newvar = json_decode($string);
   
// printing the decoded data  
print_r($newvar);
  
?>


Output:

Array
(
    [0] => hello
    [1] => 42
    [2] => Array
        (
            [0] => 1
            [1] => two
        )

    [3] => apple
)

Note: JSON encoding and decoding is more compact, and best of all, compatible with javascript and many other languages. However, for complex objects, some information may be lost.



Similar Reads

How to get YouTube video data by using YouTube data API and PHP ?
Thumbnails are used for a preview of a single or group of media entities in a single explorer window. It saves time and gives a better focus to the user's attention and help us grab attention and educate viewer enhancing web design project. The description is a few words more than the title. The more words in the YouTube video description, the poss
5 min read
How to use cURL to Get JSON Data and Decode JSON Data in PHP ?
In this article, we are going to see how to use cURL to Get JSON data and Decode JSON data in PHP. cURL: It stands for Client URL.It is a command line tool for sending and getting files using URL syntax.cURL allows communicating with other servers using HTTP, FTP, Telnet, and more. Approach: We are going to fetch JSON data from one of free website,
2 min read
PHP 5 vs PHP 7
PHP is a server side scripting language designed for web development by Rasmus Lerdorf in 1994. Since its launch in 1994 PHP has become an industry standard supporting almost 80% of the websites ( 79.8% to be precise) with its closest competitor being ASP.Net at 19.8% and others like Ruby, Java trailing far behind. The PHP development team released
4 min read
PHP | Get PHP configuration information using phpinfo()
PHP provides us with a built-in function phpinfo() which gives us the details about the PHP version and PHP configuration of PHP installed in our system. To know about the Configurations and PHP version which is installed in your computer, a simple PHP script can be used. The script consists of a PHP function called "phpinfo()" which outputs inform
2 min read
How to include content of a PHP file into another PHP file ?
Including the content of a PHP file into another file reduces the complexity of code by reducing the code and improving its modularity by splitting the code into different files so that it is easy to understand and manage. There are two ways to do it by using the following PHP functions. PHP include() Function: It will show the warning if the file
2 min read
What is New in PHP Type Hinting Support in PHP 8?
PHP 8 introduced several enhancements and new features related to type hinting. That will check the code for their respective type so that we can use our code efficiently. These are the following features used in PHP Type Hitting Support: Table of Content Union TypesMixed TypeStatic Return TypeInheritance of Contravariant ParametersInheritance of P
3 min read
PHP SPL Data structures Complete Reference
Standard PHP Library (SPL) the collection of standard data structures. The SPL data structure grouped the contents according to their implementation. Example: Below programs illustrate the SplDoublyLinkedList::offsetGet() function in PHP: C/C++ Code &lt;?php // Declare an empty SplDoublyLinkedList $list = new \SplDoublyLinkedList; // Use SplDoublyL
4 min read
How to get form data using POST method in PHP ?
PHP provides a way to read raw POST data of an HTML Form using php:// which is used for accessing PHP’s input and output streams. In this article, we will use the mentioned way in three different ways. We will use php://input, which is a read-only PHP stream. We will create a basic HTML form page where we can use all the possible approaches one at
2 min read
CRUD Operation in MySQL Using PHP, Volley Android - Read Data
In the previous article, we have performed the insert data operation. In this article, we will perform the Read data operation. Before performing this operation first of all we have to create a new PHP script for reading data from SQL Database. Prerequisite: You should be having Postman installed in your system to test this PHP script. Create a PHP
9 min read
CRUD Operation in MySQL Using PHP, Volley Android - Insert Data
It is known that we can use MySQL to use Structure Query Language to store the data in the form of RDBMS. SQL is the most popular language for adding, accessing and managing content in a database. It is most noted for its quick processing, proven reliability, ease, and flexibility of use. The application is used for a wide range of purposes, includ
10 min read
Practice Tags :
three90RightbarBannerImg