The serialize Function

The serialize function converts a PHP variable into a string of a special format, which can be stored in a database or passed between scripts. The resulting string can be converted back into a variable using the unserialize function. The function works with any PHP data types: numbers, strings, arrays, objects.

Syntax

phpserialize(mixed $value);

Example

Serializing a simple array:

php<?php
  $arr = [1, 2, 3, 4, 5];
  $res = serialize($arr);
  echo $res;
?>

Code execution result:

php'a:5:{i:0;i:1;i:1;i:2;i:2;i:3;i:3;i:4;i:4;i:5;}'

Example

Serializing a string:

php<?php
  $str = 'abcde';
  $res = serialize($str);
  echo $res;
?>

Code execution result:

php's:5:"abcde";'

Example

Serializing an object:

php<?php
  class Test {
    public $a = 1;
    protected $b = 2;
    private $c = 3;
  }
  $obj = new Test();
  $res = serialize($obj);
  echo $res;
?>

Code execution result:

php'O:4:"Test":3:{s:1:"a";i:1;s:4:"'."\0".'*'."\0".'b";i:2;s:7:"'."\0".'Test'."\0".'c";i:3;}'

See Also

  • the unserialize function,
    which restores data from a serialized string
  • the json_encode function,
    which converts data to JSON format