O'Reilly logo

Programming PHP, 3rd Edition by Peter MacIntyre, Kevin Tatroe, Rasmus Lerdorf

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Converting Between Arrays and Variables

PHP provides two functions, extract() and compact(), that convert between arrays and variables. The names of the variables correspond to keys in the array, and the values of the variables become the values in the array. For instance, this array:

$person = array('name' => "Fred", 'age' => 35, 'wife' => "Betty");

can be converted to, or built from, these variables:

$name = "Fred";
$age  = 35;
$wife = "Betty";

Creating Variables from an Array

The extract() function automatically creates local variables from an array. The indices of the array elements become the variable names:

extract($person);                // $name, $age, and $wife are now set

If a variable created by the extraction has the same name as an existing one, the variable’s value is overwritten with that from the array.

You can modify extract()’s behavior by passing a second argument. The Appendix A describes the possible values for this second argument. The most useful value is EXTR_PREFIX_ALL, which indicates that the third argument to extract() is a prefix for the variable names that are created. This helps ensure that you create unique variable names when you use extract(). It is good PHP style to always use EXTR_PREFIX_ALL, as shown here:

$shape = "round";
$array = array('cover' => "bird", 'shape' => "rectangular");

extract($array, EXTR_PREFIX_ALL, "book");
echo "Cover: {$book_cover}, Book Shape: {$book_shape}, Shape: {$shape}";

Cover: bird, Book Shape: rectangular, Shape: round

Creating an Array from ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required