serializing

Serializing is a nice way to get a string out of more complicated data structure. It's probably mostly used to sting-alize array data, although you can serialize scalar data as well.

The result of the serialization is no nature wonder, it's just a string that describes what is serialized and a value of the serialized ... thing.

The cert guide explains it all very well, I think just maybe an example of how something looks when it's serialized would have been nice. Otherwise the serialization may sound scary and mysterious.

Here's an example:
< ?php
$s = 'PHP';
echo serialize($s);
?>
This prints:
s:3:"PHP";
Which means:

  • 's' is a string, the type of the serialized var
  • '3' is the length
  • 'PHP' is the value
  • ';' is a delimiter

A slightly more complicated example - serializing an array:

< ?php
$ar = array('PHP','key'=>'serialize');
echo serialize($ar);
?>
The result is:
a:2:{i:0;s:3:"PHP";s:3:"key";s:9:"serialize";}

  • 'a' means an array
  • 'i' as in integer
  • 'i:0' is the integer key of the first element of the array, remember when you don't specify a key, PHP assigns one

Bookmark and Share

Somewhat related posts

2 Responses to “serializing”

  1. Manda Krishna Srikanth Says:

    In the last example, if there is a double quotes or a single quote in the key or the value, those will be included directly and no string escapism is required.

    ‘He said, “..I wasn\’t thrilled..”‘);
    echo serialize($ar);
    ?>
    will output,
    a:1:{s:8:”sentence”;s:32:”He said, “..I wasn’t thrilled..”";}

  2. Manda Krishna Srikanth Says:

    The previous code was this.

    ‘He said, “..I wasn\’t thrilled..”‘);
    echo serialize($ar);
    ? >

Leave a Reply