My problem is very basic.
I did not find any example to meet my needs as to what exactly serialize() and unserialize() mean in php? They just give an example – serialize an array and show an output in an unexplained format. It is really hard to understand the basic concept going through their jargon.
EDIT:
<?php
$a= array( '1' => 'elem 1', '2'=> 'elem 2', '3'=>' elem 3');
print_r($a);
echo ("<br></br>");
$b=serialize($a);
print_r($b);
?>
output:
Array ( [1] => elem 1 [2] => elem 2 [3] => elem 3 )
a:3:{i:1;s:6:"elem 1";i:2;s:6:"elem 2";i:3;s:7:" elem 3";}
I cannot understand the second output. Besides that, can anyone give an example of a situation that I need to serialize a php array before using it?
A PHP array or object or other complex data structure cannot be transported or stored or otherwise used outside of a running PHP script. If you want to persist such a complex data structure beyond a single run of a script, you need to serialize it. That just means to put the structure into a “lower common denominator” that can be handled by things other than PHP, like databases, text files, sockets. The standard PHP function
serializeis just a format to express such a thing, it serializes a data structure into a string representation that’s unique to PHP and can be reversed into a PHP object usingunserialize. There are many other formats though, like JSON or XML.Take for example this common problem:
How do I pass a PHP array to Javascript?
PHP and Javascript can only communicate via strings. You can pass the string
"foo"very easily to Javascript. You can pass the number1very easily to Javascript. You can pass the boolean valuestrueandfalseeasily to Javascript. But how do you pass this array to Javascript?The answer is serialization. In case of PHP/Javascript, JSON is actually the better serialization format:
Javascript can easily reverse this into an actual Javascript array.
This is just as valid a representation of the same data structure though:
But pretty much only PHP uses it, there’s little support for this format anywhere else.
This is very common and well supported as well though:
There are many situations where you need to pass complex data structures around as strings. Serialization, representing arbitrary data structures as strings, solves how to do this.