#5: Turning an Array into a Nonarray Variable That Can Be Restored Later

Although arrays are tremendously useful, there are some places where they're just not welcome. You can't directly store an array inside a cookie or a session, for instance. MySQL and XML can't handle the native PHP array type, either.

Fortunately, there's a way to transform PHP arrays into strings that you can store nearly anywhere: the serialize() function. Here's a script that illustrates how this function works (assume $alacarte is the same as it was in the preceding section):

<?php

$menu = array(
    "appetizer" => "fruit",
    "entree" => "roast beef",
    "dessert" => $alacarte);

$menu_s = serialize($menu); 

echo $menu_s; 

?>

Running this script produces the following output:

PEa:3:{s:9:"appetizer";s:5:"fruit";s:6:"entree";s:10:"roast ...

Get Wicked Cool PHP now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.