We have seen about PHP string extract few days before, to get particular portion of given input string using PHP in built functions, like, substr(), mb_substr() and etc. And now, we are going to see another PHP function to extract given associative array.
This function is named as extract(), that is, for extracting each of the key and value of an array, to create PHP variable with the name of array key , which will be associated with appropriate array value.
This function accepts three arguments as listed below.
Among the above list of arguments of PHP extract() function, $input_array is only the mandatory argument, whereas, the rest of them are optional that could be used on need basis.
And, behavior of this function with respect to add prefix for PHP variables, will be varied depends on the value of $extract_type parameter. So, we need to know all the available list of PHP constants used for specifying extract type.
<?php $partA = ""; $partB = ""; $input_array = array("partA" => "Stories","partB" => "Rhymes", "partC" => "Concepts"); extract($input_array,EXTR_IF_EXISTS); print '$partA='. $partA . '<br/>'; print '$partB='. $partB . '<br/>'; print '$partC='. $partC . '<br/>'; ?>
Note: As we have defined $partA and $partB before extract, then, this function will extract and overwrite these variables stored in current symbol table. And then, $partC is not defined previously, there is no such variable in symbol table, and hence, extract() will omit the element containing undefined variable names. And return PHP notice error as follows.
$partA=Stories $partB=Rhymes Notice: Undefined variable: partC in D:\php_env\htdocs\php_samples\php_extract.php on line 8 $partC=
<?php $input_array = array("partA" => "Stories","partB" => "Rhymes", "partC" => "Concepts"); print "<strong>Before Extract:</strong><br/>"; print_r($input_array); extract($input_array,EXTR_REFS); $partA = "Alphabets"; print "<br/><br/><strong>After Extract:</strong><br/>"; print_r($input_array); ?>
Note: $input_array[“partA”] is changed by using $partA variable reference, that we can see with the following output of this program.
Before Extract: Array ( [partA] => Stories [partB] => Rhymes [partC] => Concepts ) After Extract: Array ( [partA] => Alphabets [partB] => Rhymes [partC] => Concepts )
Added to the above list of PHP extract type constants, some more constants are there in use. These are the flag to add third argument $variable_prefix at the beginning of each variable created on extract, separated with (_) underscore symbol.
It is not good programming practice to use this extract() function with PHP global array, Why because,
This PHP code tutorial was published on July 30, 2013.