Tác dụng của hàm extract()
The extract()
function imports variables into the current symbol table from an array.
This function basically creates variables from an associative array. This is typically done by using the array keys as variable names and their corresponding values as the variable values.
The following table summarizes the technical details of this function.
Return Value: | Returns the number of variables successfully imported into the symbol table. |
---|---|
Version: | PHP 4+ |
Syntax
The basic syntax of the extract()
function is given with:
The following example shows the extract()
function in action.
Example
Run this code »<?php
// Sample associative array
$array = array("brand"=>"Porsche", "model"=>"911", "color"=>"blue");
// Extracting variables
extract($array);
echo "Brand: $brand, Model: $model, Color: $color";
?>
Tip: If an existing variable has the same name as one of the keys in the associative array, a collision will occur, and the extracted variable overwrites the existing variable. Also, if any key in the associative array is not a valid variable name it won't be extracted. However, the default behavior of this function can be changed by setting the flags and prefix parameter.
Warning: Do not use the extract()
function on untrusted data, such as user input received through a web form (e.g. $_GET
, $_FILES
), as it poses a potential security risk.
Parameters
The extract()
function accepts the following parameters.
Parameter | Description |
---|---|
array | Required. Specifies an array to use. |
flags |
Optional. Specifies how invalid or numeric keys and collisions are treated. This parameter can take one of the following values:
If this parameter is not specified, it is assumed to be |
prefix |
Optional. Specifies the prefix string. Prefixes are automatically separated from the array key by an underscore ( This parameter is only required if flags is set to any of these values
EXTR_PREFIX_SAME , EXTR_PREFIX_ALL , EXTR_PREFIX_INVALID or EXTR_PREFIX_IF_EXISTS . |
More Examples
Here're some more examples showing how extract()
function basically works:
The following example shows how to prevent overwriting of existing variable if a collision occurs.
Example
Run this code »<?php
// Variable name same as array key
$color = "red";
// Sample associative array
$array = array("brand"=>"Porsche", "model"=>"911", "color"=>"blue");
// Extracting variables
extract($array, EXTR_PREFIX_SAME, "car");
echo "$brand, $model, $color, $car_color";
?>
The following example prevent overwriting an existing variable on collision by skipping extraction.
Example
Run this code »<?php
// Variable name same as array key
$color = "red";
// Sample associative array
$array = array("brand"=>"Porsche", "model"=>"911", "color"=>"blue");
// Extracting variables
extract($array, EXTR_SKIP);
echo "$brand, $model, $color";
?>