The extract()
function converts elements in an array into variables.
PHP extract() Function has the following syntax.
int extract ( array arr [, int options [, string prefix]] )
Parameter | Is Required | Description |
---|---|---|
array | Required. | Array to use |
extract_rules | Optional. | The extract() function checks for invalid variable names and collisions with existing variable names. This parameter specifies how invalid and colliding names are treated. |
prefix | Optional. | 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:
Value | Meaning |
---|---|
EXTR_OVERWRITE | Default. On collision, overwrite the existing variable |
EXTR_SKIP | On collision, the existing variable is not overwritten |
EXTR_PREFIX_SAME | On 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 |
Convert array to variables
<?PHP
$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.
Use different extract mode
<?Php/*w ww . j av a2s . c om*/
$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.