Turning Array into NonArray Variable and Restore It Back

Thursday, February 5, 2009

Array is useful, but it's not silver bullet. There are some conditions that we can't use array. Saving an array into a session or cookie directly, for instance. XML and MySQL can't handle native PHP array type either.

That's where the function serialize come in handy. And here's a script that shows how this function works:

<?php
$drinks = array("lemon squash",
                  "capuccino",
                  "soda");
$dinners = array(
    "salad" => "spinach",
    "main" => "tenderloine",
    "drink" => $drinks);

$dinners_s = serialize($dinners); 

echo $dinners_s; 

?>
The outputs:
PEa:3:{s:5:"salad";s:6:"spinach";s:4:"main";s:11:"tenderloine";s:5:"drink";a:3:{i:0;s:12:"lemon squash";i:1;s:9:"capuccino";i:2;s:4:"soda";}}

THe serialized variable $dinners_s can be stored in almost anywhere -database, hiddem input variable, cookies, session, and so on. And You only need a line of code to restore it back to array

$dinners = deserialize($dinners_s)

But keep in mind, serialized arrays can be read easily by people so you might need to encrypt them so that nobody can't sniff your data. Secondly, don't pass serialized arrays through GET method because URL's length have finite length. And last one, don't overuse it, when you start to get and store serialized arrays consistently, maybe it's time for you to redesign your storage mechanism or database structure.

Hope it helps.

0 comments: