In this post I’ll explain how to easily transfer/convert Arrays into a format that can easily be stored. We use serialize()
and unserialize()
functions of Php for this purpose. These functions allow you to convert arrays into string format and then you can later retrieve them as required.
Serialization:
Serialization is a process in which we convert an array into a string format. This is useful to store arrays in a database or to pass them between pages.
// Example: Serializing an array
$myArray = array(
"name" => "John Doe",
"email" => "john@example.com",
"age" => 30
);
$serializedArray = serialize($myArray);
echo $serializedArray;
In the example above, the array will be converted into a serialized string and output would be:
a:3:{s:4:"name";s:8:"John Doe";s:5:"email";s:15:"john@example.com";s:3:"age";i:30;}
This returned string can now be stored or used as needed.
Unserialization:
Unserialization is the reverse process where the serialized string is converted back into its original array format. The function unserialize()
is used for this purpose.
// Example: Unserializing the array
$retrievedArray = unserialize($serializedArray);
print_r($retrievedArray);
The output will be the original array:
Array
(
[name] => John Doe
[email] => john@example.com
[age] => 30
)
Why Use Serialization?
- Storing Arrays in a Database: One of its main uses is to store an array into a database as databases only support simple data types like strings. Serializing an array will allow to store data in a single column in the database..
- Transfer Data: When you need to pass an array between pages via GET or POST, serialization can be very useful.
Common Use Cases
// Storing serialized array in a database
$serializedArray = serialize($myArray);
// Insert into a database or other storage
// Retrieve and unserialize it later
$retrievedArray = unserialize($serializedArray);