Home>Article>Backend Development> Why do php arrays need to be serialized?

Why do php arrays need to be serialized?

王林
王林 Original
2019-09-19 11:53:38 2053browse

Why do php arrays need to be serialized?

When we want to store an array value into the database, we can serialize the array and then store the serialized value in the database. In fact, PHP serialized arrays convert complex array data types into strings to facilitate array storage operations.

To serialize and deserialize PHP arrays, two functions are mainly used,serializeandunserialize.

1. PHP array serialization: serialize

$arr = array('PHP','Java','Python','C'); $result = serialize($arr); echo $result;

Run result:

Why do php arrays need to be serialized?

a: Indicates the overall data type, here is array;

4 in a:4: indicates the number of array elements;

i: indicates int, integer type;

0: Indicates the subscript of the array element;

s: Indicates string, that is, the type of the array value;

s: 3 in 3: Indicates the length of the array value.

ps: serialize() returns a string. This string contains a byte stream representing value and can be stored anywhere. This facilitates storing or passing PHP values without losing their type and structure.

2. PHP deserialization: unserialize

$arr = array('PHP','Java','Python','C'); $result = serialize($arr); var_dump(unserialize($result));

Result:

Why do php arrays need to be serialized?

ps: unserialize() operates on a single serialized variable and converts it back to a PHP value.

Recommended tutorial:PHP video tutorial

The above is the detailed content of Why do php arrays need to be serialized?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn