PHP extract is a function that breaks an array into variables

  • 2020-03-31 20:51:11
  • OfStack

Extract () function syntax:
Int extract(array $var_array [, int $extract_type = EXTR_OVERWRITE [, string $prefix]])
Function: extract() function extracts associative array (invalid for numeric index array) for each pair of key and value, and generates multiple sets of new variables with key as variable name and value as corresponding value.
 
<?php 
$size = "old size"; //Notice the value of the last size variable.
$a = array( 
"color" => "red", 
"size" => "XXL", 
"price" => "53"); 
extract($a); 
echo "color = $color<br />"; 
echo "size = $size<br />"; 
echo "price = $price<br />"; 
?> 


The result is:

Color = red
Size = XXL
Price = 53

It is found from the above example that the value of $size is XXL instead of the previous "old size", which means that when the key in the array conflicts with the existing variable by default, the original variable will be overwritten.

Continue with the last two optional parameters of the extract function.

The second parameter, $extract_type, is used to control the handling method when a conflict occurs. The possible value is:

EXTR_OVERWRITE: overwrites an existing variable when it conflicts, default.
EXTR_SKIP: does not override existing variables, that is, variables that do not generate the key and value pairs.
When EXTR_PREFIX_SAME: conflicts, the new variable name is generated with a prefix string whose value is specified by the third argument.
EXTR_PREFIX_ALL: adds a prefix string to all generated new variable names, whose value is specified by the third argument.
EXTR_PREFIX_INVALID: when the value of a key is changed to a variable name that is invalid (if the key starts with a number and the variable name requires that the first character not be a number), add a prefix string to the variable name, whose value is specified by the third argument.
EXTR_IF_EXISTS: only takes variables that already exist.
EXTR_PREFIX_IF_EXISTS: a variable obtained for EXTR_IF_EXISTS, with a prefix string in its variable name, whose value is specified by a third argument.
EXTR_REFS: extract a variable by reference, indicating that a change in the value of the extracted variable affects the value of the original array.

Note: when the variable name is prefixed with a string, the new variable is called PREFIX_key, not PREFIXkey.

 
<?php 
$a = array( 
"color" => "red", 
"size" => "XXL", 
"price" => "53"); 
extract($a,EXTR_PREFIX_ALL,"SC"); 
echo "color = $SC_color<br />"; 
echo "size = $SC_size<br />"; 
echo "price = $SC_price<br />"; 
extract($a,EXTR_REFS); 
$color="green"; 
echo $a['color']; //View the value of the original array
?> 

The result is:
Color = red
Size = XXL
Price = 53
Green,

Related articles: