PHP extract() Function

PHP extract Function


Definition :

In PHP Array function the xtract() 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.

Syntax
The basic syntax of the extract() function is given with:

extract(array, extract_rules, prefix)

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:

  • EXTR_OVERWRITE - On collision, overwrite the existing variable.
  • EXTR_SKIP - On collision, do not overwrite the existing variable.
  • EXTR_PREFIX_SAME - On collision, prefix the variable name with the prefix.
  • EXTR_PREFIX_ALL - Prefix all variable names with the prefix.
  • EXTR_PREFIX_INVALID - Only prefix invalid or numeric variable names with prefix.
  • EXTR_IF_EXISTS - Only overwrite the variable if it already exists, else do nothing.
  • EXTR_PREFIX_IF_EXISTS - Only create prefixed variable names if the non-prefixed version of the same variable already exists.
  • EXTR_REFS - Extract variables as references rather than copies. This means that the values of the imported variables are still referencing the values of the array parameter.

If this parameter is not specified, it is assumed to be EXTR_OVERWRITE.

prefix

Optional. Specifies the prefix string. Prefixes are automatically separated from the array key by an underscore (_). If the prefixed result is not a valid variable name, it is not extracted.

This parameter is only required if flags is set to any of these values EXTR_PREFIX_SAMEEXTR_PREFIX_ALLEXTR_PREFIX_INVALID or EXTR_PREFIX_IF_EXISTS.

Example1 : Below example shows the extract() function in action.

Output :

Example2: following example shows how to prevent overwriting of existing variable if a collision occurs.
 

Output :