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
<?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
<?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
<?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
<?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.