PHP extract() Function
The PHP extract() function imports variables from an array into the current symbol table. It converts array keys into variable names and array values into variable values. For each key/value pair it creates a variable in the current symbol table, subject to flags and prefix parameters.
This function checks each key to see whether it has a valid variable name. It also checks for collisions with existing variables in the symbol table.
Syntax
extract(array, flags, prefix)
Parameters
array |
Required. Specify an array to use. It must be an associative array. A numerically indexed array will not produce results unless EXTR_PREFIX_ALL or EXTR_PREFIX_INVALID parameter is used. |
flags |
Optional. Specify the way invalid/numeric keys and collisions are treated is determined by the extraction flags. It can be one of the following values:
|
prefix |
Optional. Specify prefix. It is only required if flags is EXTR_PREFIX_SAME, EXTR_PREFIX_ALL, EXTR_PREFIX_INVALID or EXTR_PREFIX_IF_EXISTS. If the prefixed result is not a valid variable name, it is not imported into the symbol table. Prefixes are automatically separated from the array key by an underscore character.
|
Return Value
Returns the number of variables successfully imported into the symbol table.
Example: extract() example
The example below shows the usage of extract() function.
<?php //the input array $arr = array("color" => "red", "size" => 10, "shape" => "cube"); extract($arr); //after using extract() function echo "\$color = $color \n"; echo "\$size = $size \n"; echo "\$shape = $shape \n"; ?>
The output of the above code will be:
$color = red $size = 10 $shape = cube
Example: handling collision
In the example below, there is a collision due to $color variable. But this variable is not overwritten because the EXTR_PREFIX_SAME flag is used which resulted in $new_color variable being created.
<?php $color = "black"; //the input array $arr = array("color" => "red", "size" => 10, "shape" => "cube"); extract($arr, EXTR_PREFIX_SAME, "new"); //after using extract() function echo "\$color = $color \n"; echo "\$size = $size \n"; echo "\$shape = $shape \n"; echo "\$new_color = $new_color \n"; ?>
The output of the above code will be:
$color = black $size = 10 $shape = cube $new_color = red
❮ PHP Array Reference