Backend Development 4 min read

Using PHP extract() to Convert Array Elements into Variables

This article explains the PHP extract() function, its syntax, parameters, return value, and provides two practical code examples showing how to turn associative array entries into individual variables with optional prefix handling.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Using PHP extract() to Convert Array Elements into Variables

In everyday PHP development it is common to need each element of an associative array to become a separate variable; the built‑in extract() function simplifies this process.

The function signature is:

<code>extract(array $arr, int $flags = EXTR_OVERWRITE, string $prefix = "")</code>

Parameters:

$arr : an associative array (numeric‑indexed arrays are ignored unless specific flags are used).

$flags : optional integer that determines how to handle invalid, numeric, or conflicting keys (e.g., EXTR_OVERWRITE , EXTR_PREFIX_SAME , etc.).

$prefix : optional string used when certain flags are set ( EXTR_PREFIX_SAME , EXTR_PREFIX_ALL , EXTR_PREFIX_INVALID , EXTR_PREFIX_IF_EXISTS ); a leading underscore is added between the prefix and the original key.

The function returns the number of variables successfully imported into the symbol table.

Example 1 – Using only the array argument:

<code>&lt;?php
$arr = array(
    "name" => "张三",
    "age" => "27",
    "gender" => "男",
    "profession" => "法外狂徒"
);
$extract_num = extract($arr);
 echo $extract_num . "&lt;br&gt;";
 echo $name . "&lt;br&gt;";
 echo $age . "&lt;br&gt;";
 echo $gender . "&lt;br&gt;";
 echo $profession . "&lt;br&gt;";
?&gt;</code>

Output: 4 and the values 张三, 27, 男, 法外狂徒.

Example 2 – Using three arguments with a prefix:

<code>&lt;?php
$profession = "职业张三";
$arr = array(
    "name" => "张三",
    "age" => "27",
    "gender" => "男",
    "profession" => "法外狂徒"
);
$extract_num = extract($arr, EXTR_PREFIX_SAME, "wddx");
 echo $extract_num . "&lt;br&gt;";
 echo $name . "&lt;br&gt;";
 echo $age . "&lt;br&gt;";
 echo $gender . "&lt;br&gt;";
 echo $profession . "&lt;br&gt;";
 echo $wddx_profession . "&lt;br&gt;";
?&gt;</code>

Because the $flags value EXTR_PREFIX_SAME is used, the original $profession variable is not overwritten; instead a new variable $wddx_profession is created with the specified prefix.

This demonstrates how extract() can safely import array data while avoiding variable name collisions.

BackendarrayTutorialvariablesextract
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.