I'm using PHP 7.1.12 and I'm trying to understand the functionality of one of the most important built-in functions in PHP serialize()

I understood that serialize() is used to generate a storable representation of a value which is passed to it.

I think it means serialize() converts the received value into some string using its internal functionality. Is this my perception right about serialize()?

Consider below code :

<?php

$a = [];
$a[] = $a;
echo "\na: ".serialize($a);

$b = [];
$b[] =& $b;
echo "\nb: ".serialize($b);

Output :

a: a:1:{i:0;a:0:{}}
b: a:1:{i:0;a:1:{i:0;R:2;}}

In the output I'm not able to understand from where the letters i, a, R are coming into the output. Also, I'm not able to understand how this output is formed by serialize()

So, my question is; As a PHP developer, is it necessary for me to understand above output or should I directly make use of this output without going into the details of it?

Please guide me in this regard.

2

There are 2 answers

3
Kamal Soni On BEST ANSWER

The below is the general explanation of what those characters mean.

String

s:size:value;

Integer

i:value;

Boolean

b:value; (store '1' or '0')

Null

N;

Array

a:size:{key definition;value definition;(repeated per element)}

Object

O:strlen(object name):object name:object size:{s:strlen(property name):property name:property definition;(repeated per property)}

It is not really necessary for us to know, how PHP serializes, but if you are are curious, the above explanation would help to understand that there is some logic to it. I hope this helps.

0
Sumit Kumar On

Another feature of PHP’s serialization format is that it will properly preserve references: The important part here is the R:2; element. It means “reference to the second value. As objects in PHP exhibit a reference-like behavior serialize also makes sure that the same object occurring twice will really be the same object on unserialization:

$b = [];
$b[] =& $b;
echo "\nb: ".serialize($b);

output:b: a:1:{i:0;a:1:{i:0;R:2;}}

The whole array is the first value, the first index is the second value, so that’s what is referenced.