php serialize codeSo the other day I was working on how to build a chess application with PHP. I started to think about building the board by creating a array with eight sub arrays. This allows me to make the whole board and single variable. This was easy to set up. Then I realized how will i save this to a data base? The answer to this is a two functions serialize() and unserialize(). What they do is take an array and tern it into a savable text string. For example if you take the code.

//Creates an array
$array = array('one'=>1,'two'=>2);
//Serializes the array (makes is savable)
$array_unserialized = serialize($array);
//Echos out the array.
echo $array_unserialized;

This code out puts a:2:{s:3:”one”;i:1;s:3:”two”;i:2;} The nice thing about the serialize functions is that you can also send it multidimensional arrays. To tern it back into a usable array you would do.

//Terns the array back to the array.
$array_new = unserialize($array_unserialized);
//Does something with the array.

This code outputs you guessed it array(2) { [“one”]=> int(1) [“two”]=> int(2) }

Just a little handy tool.

Warning: Don’t pass user data to unserialize() a malicious user can use it to exploit your site. To find out more look at and look under Notes.