Home >Backend Development >PHP Tutorial >Detailed explanation of PHP serialization and deserialization function examples
This article mainly introduces PHP serialization and deserialization functions. Friends in need can refer to
Serialization and Deserialization
to simplify the complex Compress the data type into a string
serialize() Encode variables and their values into text form
unserialize() Restore the original variables
1 .Create an $arr array to store basic user information and output the viewing results in the browser;
$arr=array(); $arr['name']='张三'; $arr['age']='22'; $arr['sex']='男'; $arr['phone']='123456789'; $arr['address']='上海市浦东新区'; var_dump($arr);
Output results:
array(5) { ["name"]=> string(6) "张三" ["age"]=> string(2) "22" ["sex"]=> string(3) "男" ["phone"]=> string(9) "123456789" ["address"]=> string(21) "上海市浦东新区" }
2. Serialize the $arr array and assign it to the $info string, and output the viewing result in the browser;
$info=serialize($arr); var_dump($info);
Output result:
string(140) "a:5:{s:4:"name";s:6:"张三";s:3:"age";s:2:"22";s:3:"sex";s:3:"男";s:5:"phone";s:9:"123456789";s:7:"address";s:21:"上海市浦东新区";}"
Use the serialize($arr) function to serialize the array The keys and values of the elements in the string are concatenated into strings in regular order. The a:5 flag is serialized into an array containing 5 key-value pairs, and the s:4 flag content is a string containing 4 characters.
Through serialization, we can store some modular data in the form of strings in the database or session, etc., which can reduce the creation of many cumbersome data table fields. Of course, serialization as string storage will Adding extra space should be properly designed and applied.
3. Finally, use unserialize($info) to deserialize and restore the string to the array pattern we need;
$zhangsan=unserialize($info); var_dump($zhangsan);
Output result:
array(5) { ["name"]=> string(6) "张三" ["age"]=> string(2) "22" ["sex"]=> string(3) "男" ["phone"]=> string(9) "123456789" ["address"]=> string(21) "上海市浦东新区" }
Related recommendations:
Detailed explanation of PHP serialization and deserialization
Comparison of php serialization function serialize and native method
##
The above is the detailed content of Detailed explanation of PHP serialization and deserialization function examples. For more information, please follow other related articles on the PHP Chinese website!