Wednesday 31 July 2013

Serialize and Unserialize the datas in php

Serialize is used for storing and passing the values without losing their type and structure in PHP. If we need to store or pass the values without losing their type and structure use the function serialize as serialize() . Serialize() converts an array into the string values.

      For example: serialize(array('codetruster', 'php', 'css')) 
      Then this will be output a:3:{i:0;s:11:"codetruster";i:1;s:3:"php";i:2;s:3:"css";}

Unserialize is used to convert the actual data from the Serialized data. unserialize is used to convert the string datas into an array and display it on the browser. To convert the string datas into an array using the function unserialize().


      For example: 
                           array
  0 => string 'codetruster' (length=11)
  1 => string 'php' (length=3)
  2 => string 'css' (length=3)

Download Coding : Serialize and Unserialize datas in php



<?php
$array = array(
    'first_name' => 'suganya',
    'last_name' => 'jayaraman',
    'email' => 'sugan [at] jayaraman [dot] com',
    'location' => 'India',
);
echo '<h3>Before Serialization</h3>';
var_dump($array);
 
echo '<h3>After Serialization</h3>';
$serialized_array = serialize($array);
var_dump($serialized_array);
?>
<hr />
<?php
echo '<h3>After UnSerialization</h3>';
$unserialized_array = unserialize($serialized_array);
var_dump($unserialized_array);
?>

This will be the output :

Before Serialization

array
  'first_name' => string 'suganya' (length=7)
  'last_name' => string 'jayaraman' (length=9)
  'email' => string 'sugan [at] jayaraman [dot] com' (length=30)
  'location' => string 'India' (length=5)

After Serialization

string 'a:4:{s:10:"first_name";s:7:"suganya";s:9:"last_name";s:9:"jayaraman";s:5:"email";s:30:"sugan [at] jayaraman [dot] com";s:8:"location";s:5:"India";}' (length=147)

After UnSerialization

array
  'first_name' => string 'suganya' (length=7)
  'last_name' => string 'jayaraman' (length=9)
  'email' => string 'sugan [at] jayaraman [dot] com' (length=30)
  'location' => string 'India' (length=5)

No comments:

Post a Comment