PHP extract() Function

Definition

The extract() function converts elements in an array into variables.

Syntax

PHP extract() Function has the following syntax.

int extract ( array arr [, int options [, string prefix]] )

Parameter

ParameterIs RequiredDescription
arrayRequired.Array to use
extract_rulesOptional.The extract() function checks for invalid variable names and collisions with existing variable names. This parameter specifies how invalid and colliding names are treated.
prefixOptional.If EXTR_PREFIX_SAME, EXTR_PREFIX_ALL, EXTR_PREFIX_INVALID or EXTR_PREFIX_IF_EXISTS are used in the extract_rules parameter, a specified prefix is required.

Possible values for extract_rules:

ValueMeaning
EXTR_OVERWRITEDefault. On collision, overwrite the existing variable
EXTR_SKIP On collision, the existing variable is not overwritten
EXTR_PREFIX_SAMEOn collision, the variable name will be given a prefix
EXTR_PREFIX_ALL All variable names will be given a prefix
EXTR_PREFIX_INVALID Use the prefix specified by parameter three for illegal names
EXTR_IF_EXISTS Set variables only if they already exist
EXTR_PREFIX_IF_EXISTS Create prefixed variables only if non-prefixed version already exists
EXTR_REFS Extract variables as references rather than copies

Example 1

Convert array to variables


<?PHP//from   www.j  a  va  2  s.c  o  m
$W = "W";
$capitalcities = array("E"=>"e", "A"=>"a", "W"=>"java2s.com");
extract($capitalcities);
print $W;
?>

After calling extract, the E, A, and W keys become variables ($E, $A, and $W), with their values set to e, a, and java2s.com, respectively.

By default, extract() will overwrite any existing variables.

Its second parameter tells how values will be treated if there is an existing variable, and parameter three allows you to prefix each extract variable with a special string.

The last option, EXTR_REFS, can be used on its own or in combination with others using the bitwise OR operator, |.

The code above generates the following result.

Example 2

Use different extract mode


<?Php// www.  ja va2  s  . c o  m
$capitalcities = array("E"=>"e", "A"=>"a", "W"=>"java2s.com");
$W = 'oldValue';
extract($capitalcities, EXTR_SKIP);
// leaves $W intact, as it exists already

print $W;
print $A;

extract($capitalcities, EXTR_PREFIX_SAME, "pre");
// creates variables $pre_W, $pre_A, etc

print $W;
print $pre_E;

extract($capitalcities, EXTR_PREFIX_ALL, "preAll");
extract($capitalcities, EXTR_PREFIX_ALL | EXTR_REFS, "pre");
?>

The code above generates the following result.





















Home »
  PHP Tutorial »
    Function reference »




PHP Array Functions
PHP Calendar Functions
PHP Class Functions
PHP Data Type Functions
PHP Date Functions
PHP File Functions
PHP Image Functions
PHP Math Functions
PHP MySQLi Functions
PHP SimpleXML Functions
PHP String Functions
PHP XML Functions
PHP Zip Functions