The extract( )
function automatically creates local variables from an array. The indexes of the array elements are the variable names:
$person = array('name' => 'Fred', 'age' => 35, 'wife' => 'Betty');
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 extracted variable overwrites the existing variable.
The compact( )
function is the complement of extract( )
. Pass it the variable names to compact either as separate parameters or in an array. The compact( )
function creates an associative array whose keys are the variable names and whose values are the variable's values. Any names in the array that do not correspond to actual variables are skipped. Here's an example of compact( ) in action:
$color = 'indigo'; $shape = 'curvy'; $floppy = 'none';
$a = compact('color', 'shape', 'floppy');
// or
$names = array('color', 'shape', 'floppy');
$a = compact($names);