Home >Backend Development >PHP Tutorial >PHP serialization functions serialize() and unserialize() compared with native functions, PHP serialization functions_PHP tutorial

PHP serialization functions serialize() and unserialize() compared with native functions, PHP serialization functions_PHP tutorial

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-07-13 09:54:42895browse

php serialization functions serialize() and unserialize() Compared with native functions, php serialization function

php has the function of formatting strings and converting them into arrays or objects. Method, that is, serialization processing.
There are two ways to serialize variables.

The following example, using the serialize() and unserialize() functions:

// a complex array
$myvar = array(
 'hello',
 42,
 array(1,'two'),
 'apple'
);

// convert to a string
$string = serialize($myvar);

echo $string;
/* prints
a: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);
/* prints
Array
(
  [0] => hello
  [1] => 42
  [2] => Array
    (
      [0] => 1
      [1] => two
    )

  [3] => apple
)
*/

This is the native PHP serialization method.

However, due to the popularity of JSON in recent years, support for the JSON format has been added to PHP5.2.

Now you can use json_encode() and json_decode() functions:

// 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);
/* prints
Array
(
  [0] => hello
  [1] => 42
  [2] => Array
    (
      [0] => 1
      [1] => two
    )

  [3] => apple
)
*/

This will be more efficient and especially compatible with many other languages ​​such as JavaScript.

Note: For complex objects, some information may be lost.

The above is the entire content of this article, I hope you all like it.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/996220.htmlTechArticlephp serialization functions serialize() and unserialize() Compared with native functions, the php serialization function php has formats A good way to convert a string into an array or object is serialization. ...
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