Current Location: Home> Latest Articles> Introduction to serialize function: How to convert PHP variables to strings?

Introduction to serialize function: How to convert PHP variables to strings?

gitbox 2025-05-27

In PHP, serialize is a very important function to convert PHP variables into strings that can be stored or transferred. This is useful for saving complex PHP data structures (such as arrays, objects) to a database, file system, or transferring on a network. Next, we will dig into how serialize functions work and how to use it to handle PHP variables.

What is the serialize function?

The function of the serialize function is to convert PHP variables (such as arrays, objects, etc.) into a storable string format. With this function, we can convert complex variable data structures into strings so that they can be saved in files or transferred to other applications over the network. The reverse operation is to use the unserialize function, which can reconvert the string back to the original PHP variable.

How to use serialize function?

The syntax of the serialize function is as follows:

 string serialize ( mixed $value )
  • Parameters : This function accepts a parameter $value , which can be any type of PHP data, including arrays, objects, strings, numbers, etc.

  • Return value : Returns a string representing the serialized form of the given PHP variable.

Example 1: Serialize a simple array

 <?php
// Define a simple array
$array = array("apple", "banana", "cherry");

// Serialize arrays
$serialized_array = serialize($array);

// Output serialized string
echo $serialized_array;
?>

The output may be as follows:

 a:3:{i:0;s:5:"apple";i:1;s:6:"banana";i:2;s:6:"cherry";}

In this example, serialize converts the $array array into a long string representing the structure and content of the array.

Example 2: Serialize an object

 <?php
class Fruit {
    public $name;
    public $color;

    function __construct($name, $color) {
        $this->name = $name;
        $this->color = $color;
    }
}

// Create an object
$fruit = new Fruit("apple", "red");

// Serialize objects
$serialized_object = serialize($fruit);

// Output serialized string
echo $serialized_object;
?>

The output may be as follows:

 O:5:"Fruit":2:{s:4:"name";s:5:"apple";s:5:"color";s:3:"red";}

In this example, we serialize a Fruit object into a string and can restore it later via unserialize .

How to store or transfer PHP variables through serialize ?

One of the main application scenarios of serialize is to store variables into databases or files, or transfer them over the network. When storing data, we often serialize complex data structures (such as arrays or objects) into strings to simplify stored procedures.

Store serialized data to the database

Suppose we have a database field that holds the user's shopping cart information. The cart information is a multi-dimensional array containing items, quantity and price. We can use the serialize function to convert it to a string and save the string to the database.

 <?php
// Suppose the shopping cart is a multi-dimensional array
$cart = array(
    array("product" => "apple", "quantity" => 2, "price" => 3.5),
    array("product" => "banana", "quantity" => 1, "price" => 1.2),
    array("product" => "cherry", "quantity" => 3, "price" => 2.8)
);

// Serialize shopping cart data
$serialized_cart = serialize($cart);

// Suppose we are connected to the database and ready to insert the data
$sql = "INSERT INTO cart_table (user_id, cart_data) VALUES (1, '$serialized_cart')";
// Perform database operations
?>

When we need to get that cart data from the database, we can convert it back to a PHP array using unserialize .

 <?php
// Suppose we get serialized shopping cart data from the database
$retrieved_cart_data = "a:3:{i:0;a:3:{s:7:\"product\";s:5:\"apple\";s:8:\"quantity\";i:2;s:5:\"price\";d:3.5;}i:1;a:3:{s:7:\"product\";s:6:\"banana\";s:8:\"quantity\";i:1;s:5:\"price\";d:1.2;}i:2;a:3:{s:7:\"product\";s:6:\"cherry\";s:8:\"quantity\";i:3;s:5:\"price\";d:2.8;}}";

// use unserialize Restore the original array
$cart = unserialize($retrieved_cart_data);

// Print the restored array
print_r($cart);
?>

Output result:

 Array
(
    [0] => Array
        (
            [product] => apple
            [quantity] => 2
            [price] => 3.5
        )

    [1] => Array
        (
            [product] => banana
            [quantity] => 1
            [price] => 1.2
        )

    [2] => Array
        (
            [product] => cherry
            [quantity] => 3
            [price] => 2.8
        )
)

In this way, we can convert complex data structures into string forms for easy storage and transmission.

Things to note

  • Security : Deserializing data from untrusted sources (such as user input) may cause security issues such as PHP object injection. To prevent these problems, make sure to deserialize only trusted data, or consider using json_encode and json_decode instead of serialize and unserialize , especially when objects are involved.

  • Performance issues : Serialize may consume more memory and processing time when processing larger data structures, so be careful to use.


Summarize

With serialize and unserialize , PHP developers can easily convert complex data structures into strings for easy storage and transmission. This is very helpful for sharing data between different systems or services, or for saving data in databases and files. Remember to be cautious when handling sensitive or untrusted data to avoid security vulnerabilities.