Thursday, 25 September 2014

extract in PHP

PHP extract() function does array to variable transformation. It changes over array keys into variable names and array  values into variables values.

PHP extract() function uses array keys as variable names and values as variable values. For each element it will create a variable in the current symbol table.

PHP extract() function returns the number of variables extracted on success.

Syntax:

extract(array,extract_rules,prefix)
 
Parameters Description: 
array : Required. Required. Details the array to utilize.
extract_rules : Optional. PHP extract() function checks for invalid variable names and crashes with existing variable names. This parameter tags how invalid and impacting names are treated. Possible values:
  • EXTR_OVERWRITE - Default. On crash, the existing variable is overwritten.
  • EXTR_SKIP - On crash, the existing variable is not overwritten.
  • EXTR_PREFIX_SAME - On crash, the variable name will be given a prefix.
  • EXTR_PREFIX_ALL - All variable names will be given a prefix.
  • EXTR_PREFIX_INVALID - Only invalid or numeric variable names will be given a prefix.
  • EXTR_IF_EXISTS - Only overwrite existing variables in the present symbol table, generally do nothing.
  • EXTR_PREFIX_IF_EXISTS - Only add prefix to variables if the same variable exists in the present symbol table.
  • EXTR_REFS - Extracts variables as references. The imported in variables are still referencing the values of the array parameter.
prefix : Optional. If EXTR_PREFIX_SAME, EXTR_PREFIX_ALL, EXTR_PREFIX_INVALID or EXTR_PREFIX_IF_EXISTS are utilized within the extract_rules parameter, a specified prefix is needed.
This parameter determines the prefix. The prefix is automatically separated from the array key by an underscore character.

Example:

<?php
$a = 'Real';
$daysarr = array( "a"=>"Sunday","b"=>"Monday","c"=>"Tuesday" );
extract($daysarr);
echo "\$a = $a; \$b = $b; \$c = $c;";
echo "<br />"."with all parameter in use:";
$a = 'Real';
$daysarr = array( "a"=>"Sunday","b"=>"Monday","c"=>"Tuesday" );
extract($daysarr, EXTR_PREFIX_SAME, 'dup');
echo "\$a = $a; \$b = $b; \$c = $c; \$dup_a = $dup_a;";?>

O/P:

$a = Sunday; $b = Monday; $c = Tuesday;
with all parameter in use: 
$a = Real; $b = Monday; $c = Tuesday; $dup_a = Sunday;

0 comments:

Post a Comment