Serialization
Have you ever needed to store a complex variable in a database or a text file? You do not have to come up with a fancy solution to convert your arrays or objects into formatted strings, as PHP already has functions for this purpose.
There are two popular methods of serializing variables. Here is an example that uses the serialize() andunserialize():
|
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
// a complex array$myvar = array( 'hello', 42, array(1,'two'), 'apple');// convert to a string$string = serialize($myvar);echo $string;/* printsa: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";}*/// you can reproduce the original variable$newvar = unserialize($string);print_r($newvar);/* printsArray( [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:
|
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
// a complex array$myvar = array( 'hello', 42, array(1,'two'), 'apple');// convert to a string$string = json_encode($myvar);echo $string;/* prints["hello",42,[1,"two"],"apple"]*/// you can reproduce the original variable$newvar = json_decode($string);print_r($newvar);/* printsArray( [0] => hello [1] => 42 [2] => Array ( [0] => 1 [1] => two ) [3] => apple)*/ |
It is more compact, and best of all, compatible with javascript and many other languages. However, for complex objects, some information may be lost.