Latest web development tutorials

PHP extract () function

PHP Array Reference Complete PHP Array Reference

Examples

The key "Cat", "Dog" and "Horse" is assigned to the variable $ a, $ b and $ c:

<?php
$a = "Original";
$my_array = array("a" => "Cat","b" => "Dog", "c" => "Horse");
extract($my_array);
echo "$a = $a; $b = $b; $c = $c";
?>

Running instance »

Definition and Usage

extract () function to import an array of variables into the current symbol table.

This function uses the array key as a variable name, use the array as a key variable. For each element in the array will create a corresponding variable in the current symbol table.

The function returns the number of variables successfully set.


grammar

extract( array,extract_rules,prefix )

参数 描述
array 必需。规定要使用的数组。
extract_rules 可选。extract() 函数将检查每个键名是否为合法的变量名,同时也检查和符号表中已存在的变量名是否冲突。对不合法和冲突的键名的处理将根据此参数决定。

可能的值:

  • EXTR_OVERWRITE - 默认。如果有冲突,则覆盖已有的变量。
  • EXTR_SKIP - 如果有冲突,不覆盖已有的变量。
  • EXTR_PREFIX_SAME - 如果有冲突,在变量名前加上前缀 prefix。
  • EXTR_PREFIX_ALL - 给所有变量名加上前缀 prefix。
  • EXTR_PREFIX_INVALID - 仅在不合法或数字变量名前加上前缀 prefix。
  • EXTR_IF_EXISTS - 仅在当前符号表中已有同名变量时,覆盖它们的值。其它的都不处理。
  • EXTR_PREFIX_IF_EXISTS - 仅在当前符号表中已有同名变量时,建立附加了前缀的变量名,其它的都不处理。
  • EXTR_REFS - 将变量作为引用提取。导入的变量仍然引用了数组参数的值。
prefix 可选。如果 extract_rules 参数的值是 EXTR_PREFIX_SAME、EXTR_PREFIX_ALL、 EXTR_PREFIX_INVALID 或 EXTR_PREFIX_IF_EXISTS,则 prefix 是必需的。

该参数规定了前缀。前缀和数组键名之间会自动加上一个下划线。

technical details

return value: Returns the number of variables successfully set.
PHP version: 4+
Update log: extract_rules value EXTR_REFS is new in PHP 4.3.

extract_rules value EXTR_IF_EXISTS and EXTR_PREFIX_IF_EXISTS is new in PHP 4.2.

Since PHP 4.0.5, this function returns the number of variables successfully set.

extract_rules value EXTR_PREFIX_INVALID is new in PHP 4.0.5.

Since PHP 4.0.5, extract_rules value EXTR_PREFIX_ALL also includes numeric variables.


More examples

Example 1

Use all parameters:

<?php
$a = "Original";
$my_array = array("a" => "Cat", "b" => "Dog", "c" => "Horse");

extract($my_array, EXTR_PREFIX_SAME, "dup");

echo "$a = $a; $b = $b; $c = $c; $dup_a = $dup_a";
?>

Running instance »


PHP Array Reference Complete PHP Array Reference