PHP extract() function

PHP ksort() function
PHP list() function

In this article, you will learn how to fill the local symbol table with the variables using the keys and values of an array.

The PHP extract() function takes the keys and values from the given array and fills the local symbol table. The keys are used as the name of the variables and the values are used as the value of the variable.

Tip: You can consider the extract function as the opposite of the compact() function.

What is the syntax of the extract() function in PHP?

extract(array, extract_rules, prefix)
arrayThe array to extract variable name and value from – Required
extract_rules(optional parameter)
This parameter checks for the validity of the variable names being extracted from the array. Also, it checks if a variable name is already created by using the following possible flags.
EXTR_OVERWRITE – Existing variable is overwritten on repetition
EXTR_SKIP – The existing variable is not overwritten on repetition
EXTR_PREFIX_SAME – The variable name will be given a prefix on repetition
EXTR_PREFIX_ALL – All variable names are assigned prefix
EXTR_PREFIX_INVALID – Only invalid or numeric variable names are assigned a prefix
EXTR_IF_EXISTS – If existing variables are found, overwrite them
EXTR_PREFIX_IF_EXISTS – If existing variables are found, add the prefix to them
EXTR_REFS – Extracts variable as reference. These are still pointing to the values of the array parameter
prefixSpecify prefix which is automatically separated from the array key using an underscore (optional)
Can be used only if If EXTR_PREFIX_SAME, EXTR_PREFIX_ALL, EXTR_PREFIX_INVALID or EXTR_PREFIX_IF_EXISTS rules are applied in extract_rules parameter
PHP extract function

Examples of the extract() function

Example 1. Create some variables with values using an array.

$a = "dumy-value";
$arr= array("a" => "1","b" => "2", "c" => "3");
echo "\$a = $a; \$b = $b; \$c = $c";

Example 2. The following example shows the use of the extract() method with all parameters.

$a = "dumy-value";
$arr= array("a" => "1","b" => "2", "c" => "3");
extract($my_array, EXTR_PREFIX_SAME, "dup");
echo "\$a = $a; \$b = $b; \$c = $c; \$dup_a = $dup_a";
PHP ksort() function
PHP list() function

Add comment

Tutor Network

Share this

Learn PHP from A to Z