PHP serialization and deserialization functions

Source: Internet
Author: User

Serialization and deserialization

Compress complex data types into a string

Serialize () encodes the variables and their values into textual form unserialize () restores the original variable1. Create a $arr array to store the user's basic information and output the view results in the browser;
$arr =array ();
$arr [' name ']= ' Zhang San ';
$arr [' Age ']= ' 22 ';
$arr [' Sex ']= ' man ';
$arr [' Phone ']= ' 123456789 ';
$arr [' Address ']= ' Shanghai Pudong New Area ';
Var_dump ($arr);

Output Result:





["Address"]=> string (21) "Pudong New Area, Shanghai"
}

2. Serialize the $arr array to the $info string and output the view results in the browser;
$info =serialize ($arr);
Var_dump ($info);

Output Result:
String "A:5:{s:4:" Name "; s:6:" Zhang San "; S:3:" Age "; S:2:" N "; s:3:" Sex "; S:3:" Male "; s:5:" Phone "; S:9:" 123456789 "; s:7:" Address "; s:21:" Pudong New Area, Shanghai ";}"

Use the serialization serialize ($arr) function to concatenate the keys and values of the elements in the array into strings in a regular order. The A:5 flag is serialized as an array that contains 5 key-value pairs, and the S:4 flag content is a string containing 4 characters.
By serializing we can store some of the modular data in the form of a string, such as a database or session, can reduce the creation of a lot of tedious data table fields, of course, serialization to string storage will add additional space, should be reasonable design and application.


3. Finally use Unserialize ($info) deserialization to restore the string to the array pattern we need;
$zhangsan =unserialize ($info);
Var_dump ($zhangsan);

Output Result:
Array (5) {





}



















PHP serialization and deserialization functions

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.