Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

PHP Dictionary

  1. Home
  2. PHP Dictionary
  3. list() / compact()

list() / compact()

『list()』is a syntax for expanding (destructuring) array elements into individual variables all at once. 『compact()』generates an associative array from variable-name strings. These patterns appear frequently in『PHP』because they simplify passing data around.

Syntax

// Expand an array into variables with list()
list($var1, $var2, $var3) = $array;

// Shorthand notation using [] (PHP 7.1+)
[$var1, $var2, $var3] = $array;

// Expand an associative array by specifying keys (PHP 7.1+)
['key1' => $var1, 'key2' => $var2] = $array;

// Generate an associative array from variables with compact()
compact('varName1', 'varName2', ...);

// Expand an associative array into variables with extract() (the reverse of compact)
extract($array);

Function and Syntax Reference

Syntax / FunctionDescription
list($a, $b) = $arrExpands array elements into variables from left to right. Unwanted elements can be skipped by placing consecutive commas.
[$a, $b] = $arrShorthand notation for list(). Available from PHP 7.1. The behavior is identical; only the syntax differs.
['key' => $var] = $arrExpands a value from an associative array into a variable by specifying the key. Available from PHP 7.1.
compact('a', 'b')Collects the variables with the specified names and generates an associative array. Pass variable names as string arguments.
extract($array)Expands an associative array by using its keys as variable names and assigning the corresponding values. This is the reverse of compact(). There is a security risk, so use with care.

Sample Code

list_basic.php
<?php
// Expand array elements into multiple variables at once with list()
// Managing Evangelion pilot information in an array
$pilot = ["Ikari Shinji", "Unit-01", 14];

// list() assigns array elements to variables from left to right
list($name, $unit, $age) = $pilot;

echo $name . " / " . $unit . " / age " . $age . "\n";

// The shorthand [] produces the same result
[$name2, $unit2, $age2] = $pilot;

echo $name2 . " / " . $unit2 . " / age " . $age2 . "\n";

// Unwanted elements can be skipped by placing consecutive commas
// The unit name is not needed, so the second element is skipped
[,$unitSkip, $ageSkip] = $pilot;
echo "Unit: " . $unitSkip . " / Age: " . $ageSkip . "\n";

Running the code produces the following output:

php list_basic.php
Ikari Shinji / Unit-01 / age 14
Ikari Shinji / Unit-01 / age 14
Unit: Unit-01 / Age: 14
list_assoc.php
<?php
// Destructuring assignment with key specification to expand character information
// Specifying keys allows values to be safely retrieved without depending on index position
$rei = [
	"name" => "Ayanami Rei",
	"unit" => "Unit-00",
	"age" => 14,
	"color" => "blue",
];

// Extract only the needed values into variables by specifying keys
['name' => $reiName, 'unit' => $reiUnit, 'color' => $reiColor] = $rei;

echo $reiName . " pilots " . $reiUnit . ". Image color is " . $reiColor . ".\n";

// Combining with foreach allows concise processing of multiple characters
$pilots = [
	["name" => "Ikari Shinji", "unit" => "Unit-01", "age" => 14],
	["name" => "Ayanami Rei", "unit" => "Unit-00", "age" => 14],
	["name" => "Soryu Asuka", "unit" => "Unit-02", "age" => 14],
];

foreach ($pilots as ['name' => $pilotName, 'unit' => $pilotUnit, 'age' => $pilotAge]) {
	echo $pilotName . " (age " . $pilotAge . "): " . $pilotUnit . "\n";
}

Running the code produces the following output:

php list_assoc.php
Ayanami Rei pilots Unit-00. Image color is blue.
Ikari Shinji (age 14): Unit-01
Ayanami Rei (age 14): Unit-00
Soryu Asuka (age 14): Unit-02
compact_basic.php
<?php
// Generate an associative array from variables with compact()
// Passing a variable name as a string returns an associative array keyed by that name
$name = "Nagisa Kaworu";
$unit = "Unit-13";
$age = 17;
$series = "Rebuild";

// Simply listing variable name strings creates the associative array
$character = compact('name', 'unit', 'age', 'series');

print_r($character);

Running the code produces the following output:

php compact_basic.php
Array
(
    [name] => Nagisa Kaworu
    [unit] => Unit-13
    [age] => 17
    [series] => Rebuild
)
compact_function.php
<?php
// compact() is especially useful when assembling a return value as an associative array
function getCharacterInfo($name, $unit, $color) {
	// compact() makes constructing the return associative array concise
	return compact('name', 'unit', 'color');
}

$misato = getCharacterInfo("Katsuragi Misato", "none (commander)", "red");
$ritsuko = getCharacterInfo("Akagi Ritsuko", "none (scientist)", "white");

echo $misato['name']  . ": role " . $misato['unit']  . ", color: " . $misato['color']  . "\n";
echo $ritsuko['name'] . ": role " . $ritsuko['unit'] . ", color: " . $ritsuko['color'] . "\n";

// list() and compact() can be combined to pass values around
$data = compact('misato', 'ritsuko');
foreach ($data as ['name' => $cName, 'color' => $cColor]) {
	echo $cName . "'s color is " . $cColor . ".\n";
}

Running the code produces the following output:

php compact_function.php
Katsuragi Misato: role none (commander), color: red
Akagi Ritsuko: role none (scientist), color: white
Katsuragi Misato's color is red.
Akagi Ritsuko's color is white.

Common Mistakes

Common Mistake 1: Notice for insufficient elements when using list()

When list() receives more variables than there are elements in the array, PHP 7.3 and earlier emit E_NOTICE. The variables receive『null』. PHP 8.0 and later emit a warning when an array offset does not exist. Verify the element count before destructuring, or limit the number of variables to match the array size.

ng_list_offset.php
<?php
// The array has 2 elements but list() requests 3 variables
$pilot = ["Ikari Shinji", "Unit-01"];

list($name, $unit, $age) = $pilot; // No element exists for $age

echo $name . " / " . $unit . "\n";
echo "Age: " . $age . "\n"; // null is assigned

Running the code produces the following output:

php ng_list_offset.php
Warning: Undefined array key 2 in ...
Ikari Shinji / Unit-01
Age:

Ensure the array contains the required elements, or match the number of receiving variables to the array size.

ok_list_offset.php
<?php
$pilot = ["Ikari Shinji", "Unit-01", 14];

// Match the number of variables to the number of array elements
list($name, $unit, $age) = $pilot;

echo $name . " / " . $unit . " / age " . $age . "\n";

Running the code produces the following output:

php ok_list_offset.php
Ikari Shinji / Unit-01 / age 14

Common Mistake 2: Behavior when an undefined variable name is passed to compact()

When a variable name passed to『compact()』does not exist, PHP 7.3 and later emit E_NOTICE. The key for that variable name is not included in the returned array. This mistake is especially common with typos caused by copy-and-paste.

ng_compact_undefined.php
<?php
$name = "Ayanami Rei";
$unit = "Unit-00";

// The variable 'age' is not defined
$data = compact('name', 'unit', 'age'); // E_NOTICE: Undefined variable $age

print_r($data); // The 'age' key is not included

Running the code produces the following output:

php ng_compact_undefined.php
Warning: compact(): Undefined variable $age in ...
Array
(
    [name] => Ayanami Rei
    [unit] => Unit-00
)

Confirm that every variable name passed to compact() is already defined at that point.

ok_compact_undefined.php
<?php
$name = "Ayanami Rei";
$unit = "Unit-00";
$age = 14;

// All three variables are defined, so no Notice is raised
$data = compact('name', 'unit', 'age');

print_r($data);

Running the code produces the following output:

php ok_compact_undefined.php
Array
(
    [name] => Ayanami Rei
    [unit] => Unit-00
    [age] => 14
)

Common Mistake 3: Variable overwrite risk from extract()

By default,『extract()』overwrites any existing variable that shares a key name with the associative array. Using extract() on externally provided data ($_ GET, $_POST, DB results, etc.) introduces a security risk where unintended variables get overwritten. Limit its use to trusted internal data, and avoid using it with external data.

ng_extract_overwrite.php
<?php
$name = "Ikari Shinji"; // existing variable

// An array simulating externally received data
$externalData = [
	"name" => "Nagisa Kaworu", // overwrites $name
	"role" => "17th Angel",
];

extract($externalData); // $name is overwritten with "Nagisa Kaworu"

echo $name . "\n"; // expected "Ikari Shinji" but "Nagisa Kaworu" is output

Running the code produces the following output:

php ng_extract_overwrite.php
Nagisa Kaworu

For external data, avoid extract() and instead use key-specified destructuring or direct access.

ok_extract_overwrite.php
<?php
$name = "Ikari Shinji";

$externalData = [
	"name" => "Nagisa Kaworu",
	"role" => "17th Angel",
];

// Retrieve the needed keys directly without using extract()
$externalName = $externalData['name'];
$externalRole = $externalData['role'];

echo "Existing variable: " . $name . "\n"; // Ikari Shinji (not overwritten)
echo "External data: " . $externalName . "\n"; // Nagisa Kaworu

Running the code produces the following output:

php ok_extract_overwrite.php
Existing variable: Ikari Shinji
External data: Nagisa Kaworu

Summary

『list()』is a syntax for expanding array elements into multiple variables at once. From PHP 7.1, the shorthand notation『[]』is available, and key-specified expansion of associative arrays also became possible. The pattern of combining it with『foreach』to destructure each element of a multi-dimensional array makes code significantly more concise.

『compact()』generates an associative array from variable name strings passed as arguments.It is especially convenient for assembling multiple return values into an associative array inside a function.Because the variable name and the key name always match, it reduces the chance of typos.

『extract()』is the reverse of『compact()』; it expands an associative array using its keys as variable names. However,using『extract()』on external data ($_ GET, $_POST, DB results, etc.) carries a security risk of unexpectedly overwriting existing variables.When using it, limit it to trusted internal data only, and consider replacing it with key-specified destructuring (『list()』or『[]』) where possible. For array operations, see also『foreach』and『array_keys() / array_values()』.

If you find any errors or copyright issues, please .