PHP Array extract() Function

What is extract() Function?


The "extract()" function import variables into the current symbol table from an array. This function uses array keys as variable names, values as variable values. For each element it will create a variable in the current symbol table



In the above syntax "array" is the array from which the variables are imported to the current symbol table.

The following is the description of the Extract_rules parameters.
Parameter Description
EXTR_OVERWRITE If there is a collision, overwrite the existing variable.
EXTR_SKIP If there is a collision, don't overwrite the existing variable.
EXTR_PREFIX_SAME If there is a collision, prefix the variable name with prefix.
EXTR_PREFIX_ALL Prefix all variable names with prefix.
EXTR_PREFIX_INVALID Only invalid or numeric variable names will be given a prefix./td>
EXTR_IF_EXISTS Only overwrite existing variables in the current symbol table, otherwise do nothing
EXTR_PREFIX_IF_EXISTS Only add prefix to variables if the same variable exists in the current symbol table.
EXTR_REFS Extracts variables as references. The imported variables are still referencing the values of the array parameter.

The "prefix" parameter is seperated by an underscore, both "extract rules", "prefix" are optional parameters.

Example :

$size = "large";
$var_array = array("color" => "blue",
"size" => "medium",
"shape" => "sphere");
extract($var_array, EXTR_PREFIX_SAME, "dup");
echo "$color, $size, $shape, $dup_sizen";
Result :

blue, large, sphere, medium

In the above example there is a collision for the variable "$size" so using the extracting rule "EXTR_PREFIX_SAME", the variable $size value that is "large" is added for size and using the prefix "dup" with size, the value "medium" is displayed.

PHP Topics

Ask Questions

Ask Question