Don't understand serialize()
php
Solution
Basically, the goal of `serialize` is to transform any (alsmost) kind of data to a string, so it can be transmitted, stored, ...
A quick example :
$my_array = array(
'a' => 10,
'glop' => array('test', 'blah'),
);
$serialized = serialize($my_array);
echo $serialized;
Will get you this output :
a:2:{s:1:"a";i:10;s:4:"glop";a:2:{i:0;s:4:"test";i:1;s:4:"blah";}}
And, later, you can `unserialize` that string, to get the original data back :
$serialized = 'a:2:{s:1:"a";i:10;s:4:"glop";a:2:{i:0;s:4:"test";i:1;s:4:"blah";}}';
$data = unserialize($serialized);
var_dump($data);
Will get you :
array
'a' => int 10
'glop' =>
array
0 => string 'test' (length=4)
1 => string 'blah' (length=4)
Common uses include :
- Ability to transmit (almost) any kind of PHP data from one PHP script to another
- Ability to store (almost) any kind of PHP data in a single database field -- even if it's not quite a good practice on the database-side, it can sometimes be usefull
- Ability to store data in some caching mecanism (APC, memcached, files, ...), in which you can only store strings
Note, though, that using `serialize` is great when you are only working with PHP (as it's a PHP-specific format, that's able to work with almost any kind of PHP data, and is really fast) ; but it's not that great when you have to also work with something else than PHP (as it's PHP-specific). In those cases, you can use XML, JSON (see `json_encode` and `json_decode`), ...
In the PHP manual, you can also read the Object Serialization section, btw.
Problem
I'm looking at this function: serialize() for PHP and I don't really understand what is it's function. Can someone provide a simple example with output?