Home > Article > Backend Development > The php extract() function converts the variables in the data into php variables_PHP tutorial
The PHP extract() function imports variables from an array into the current symbol table. For each element in the array, the key name is used for the variable name and the key value is used for the variable value. The second parameter type is used to specify how the extract() function treats such conflicts when a variable already exists and there is an element with the same name in the array.
Export the variable from the PHP array and register it as a global variable, using the key name as the variable name and the value as the variable value, as follows
代码如下 | 复制代码 |
$vars = array('var1'=>'1','var2'=>'2','var3'=>'3','var4'=>'4','var5'=>'5'); |
Achieve access through key names as variable names, such as: $var1, $var2
The first option: use PHP’s built-in extract() function, the method is as follows
代码如下 | 复制代码 |
extract($vars); |
Second option: Use foreach loop array to register as a global variable, the method is as follows
代码如下 | 复制代码 |
foreach($vars as $k=>$v){ $GLOBALS[$k] = $v; } |
The second solution is recommended because the extract() function has performance and security issues.
extract() function description
(PHP 3 >= 3.0.7, PHP 4, PHP 5)
extract -- Import variables from an array into the current symbol table
The code is as follows | Copy code | ||||
|
This function is used to import variables from the array into the current symbol table. Accepts the associative array var_array as argument and uses the key name as the variable name and the value as the variable value. For each key/value pair a variable is created in the current symbol table, affected by the extract_type and prefix parameters.
Reference table
Parameters | Description | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
array | Required. Specifies the input to use. | ||||||||||||
extract_rules |
The handling of illegal, numeric and conflicting key names will be determined based on this parameter. Can be one of the following values: Possible values:
|