Like array(), this is not really a function,
but a language construct. list() is used to
assign a list of variables in one operation.
Only arrays and objects that implement ArrayAccess can be unpacked.
list() expressions can not be completely empty.
Note:
Before PHP 7.1.0, list() only worked on numerical arrays and assumes
the numerical indices start at 0.
As of PHP 7.1.0, list() can also contain explicit keys, allowing for the
destructuring of arrays with non-integer or non-sequential keys. For more details on
array destructuring, see the array destructuring section.
Note:
Attempting to access an array key which has not been defined is
the same as accessing any other undefined variable:
an E_WARNING-level error message
(E_NOTICE-level prior to PHP 8.0.0) will be
issued, and the result will be null.
Attempting to unpack a scalar assigns null to all variables.
Attempting to unpack an object that does not implement ArrayAccess is a fatal error.
Parameters
var
A variable.
vars
Further variables.
Return Values
Returns the assigned array.
Changelog
Version
Description
8.5.0
Destructuring a non-array value (other than null) now emits an
E_WARNING.
7.3.0
Support for reference assignments in array destructuring was added.
7.1.0
It is now possible to specify keys in list(). This
enables destructuring of arrays with non-integer or non-sequential keys.
Examples
Example #1 list() examples
<?php
$info = array('coffee', 'brown', 'caffeine');
// Listing all the variables
list($drink, $color, $power) = $info;
echo "$drink is $color and $power makes it special.\n";
// Listing some of them
list($drink, , $power) = $info;
echo "$drink has $power.\n";
// Or let's skip to only the third one
list( , , $power) = $info;
echo "I need $power!\n";
// list() doesn't work with strings
list($bar) = "abcde";
var_dump($bar); // NULL
?>
Example #2 An example use of list()
<?php
$result = $pdo->query("SELECT id, name FROM employees");
while (list($id, $name) = $result->fetch(PDO::FETCH_NUM)) {
echo "id: $id, name: $name\n";
}
?>
As of PHP 7.1.0 list() can now also contain
explicit keys, which can be given as arbitrary expressions.
Mixing of integer and string keys is allowed; however, elements
with and without keys cannot be mixed.