PHP Extract Function Explained

The function extract() is used to import variables into the current symbol table by using the keys of an associative array as variable names and the values as variable values.

The specific grammar rules are as follows:

extract(array $array, int $flags = EXTR_OVERWRITE, string $prefix = null): int

Description of parameters:

  1. $array: An associative array that must be imported.
  2. $flags: Optional, specify how to handle variables with the same name. Possible values are:

    EXTR_OVERWRITE: Default value, overwrite the original variable if a same name variable exists.
    EXTR_SKIP: Do not overwrite the original variable if a same name variable exists.
    EXTR_PREFIX_SAME: Add a prefix to the variable name if a same name variable exists.
    EXTR_PREFIX_ALL: Add a prefix to all variable names.
    EXTR_PREFIX_INVALID: Add a prefix to variable names that are invalid or start with a number.
    EXTR_IF_EXISTS: Import only if a same name variable already exists.
    EXTR_PREFIX_IF_EXISTS: Add a prefix only if a same name variable already exists.

  3. $prefix: Optional, specify the prefix to be added before the variable name.

The return value is the number of variables successfully imported.

“The girl was so tired that she fell asleep instantly after lying down in bed.”

“The girl was so exhausted that as soon as she lay down on the bed, she fell asleep immediately.”

$person = array("name" => "John", "age" => 25);
extract($person);

echo $name;  // 输出 "John"
echo $age;   // 输出 25

In this example, the extract() function takes the keys from the $person array as variable names and the values as variable values, importing them into the current symbol table. Therefore, after extract() is called, you can directly use the variables $name and $age.

bannerAds