PHP Serialize() Function

Arrays certainly are useful. If you’re dealing with associative data, there’s no better tool for the job. Sometimes, you’ll run into cases where it would be useful to store an entire array in a field in a database. It’s not something you want to do if you can avoid it, by structuring your database’s tables more efficiently for example, but there are cases where it’s unavoidable.

That’s where serialize() comes in. You can pass an array to the function, and it will return a string that is essentially the array flattened and mashed down. You can then unserialize() it to obtain the full array once again.

$the_array = array( "Lorem", "Ipsum", "Dolor" );
$serialized = serialize($the_array);
print $serialized;

This will output a:3:{i:0;s:5:"Lorem";i:1;s:5:"Ipsum";i:2;s:5:"Dolor";}. It’s the whole array in string form, suitable for insertion into a database field. It will work with more complex arrays, of course, but simple is better for examples.

  • Tomas

    Thank you for very simple and understandable example.

  • Vikram

    Thanks for you simple example of serialization, looking for such type of example for the so long time.

  • Nishant

    Simple and easy to understand. great

  • urbana

    thank u

  • short code

    Thanks Matt,
    It’s Really simple example.
    If anyone want more details follow

  • karmraj

    Very helpful explanation.
    Now I am more clear about this function through article than

  • Gaurav Sharma

    hey can somebody help me i am in great trouble with this code
    i have this array and now i want to store it in database into one field…please suggest me the code. thanks in advance
    $marks=array(“gaurav”=>array(“Physics”=>35, “Maths”=>30, “chemistry”=>39));

    • Dikshit

      Hey Gourav You should first serialize this array using serialize($marks); syntax and then try to insert it in database.I hope it will help you.

  • Robert


    json_encode and json_decode are an alternative and they are directly usable by javascript (and human friendly readable).

  • sanjay paratae

    anyone help me to make understand about __wakeup() and __sleep() in php by giving simple example?

    thanks in advance.

  • Patrick Reinhardt

    If you are looking for an online tool then this one is super handy

  • sohil

    how to unserialize for loop..?