list

(PHP 4, PHP 5, PHP 7, PHP 8)

list — Assign variables as if they were an array

Description

function list(mixed $var, mixed ...$vars = ?): array

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";
}
?>

Example #3 Using nested list()

<?php

list($a, list($b, $c)) = array(1, array(2, 3));

var_dump($a, $b, $c);

?>

The above example will output:

int(1)
int(2)
int(3)

The order in which the indices of the array to be consumed by list() are defined is irrelevant.

Example #4 list() and order of index definitions

<?php
$foo = array(2 => 'a', 'foo' => 'b', 0 => 'c');
$foo[1] = 'd';
list($x, $y, $z) = $foo;
var_dump($foo, $x, $y, $z);

Gives the following output (note the order of the elements compared in which order they were written in the list() syntax):

array(4) {
  [2]=>
  string(1) "a"
  ["foo"]=>
  string(1) "b"
  [0]=>
  string(1) "c"
  [1]=>
  string(1) "d"
}
string(1) "c"
string(1) "d"
string(1) "a"

Example #5 list() with keys

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.

<?php
$data = [
    ["id" => 1, "name" => 'Tom'],
    ["id" => 2, "name" => 'Fred'],
];
foreach ($data as ["id" => $id, "name" => $name]) {
    echo "id: $id, name: $name\n";
}
echo PHP_EOL;
list(1 => $second, 3 => $fourth) = [1, 2, 3, 4];
echo "$second, $fourth\n";

The above example will output:

id: 1, name: Tom
id: 2, name: Fred

2, 4

See Also

  • each() - Return the current key and value pair from an array and advance the array cursor
  • array() - Create an array
  • extract() - Import variables into the current symbol table from an array

+add a note

User Contributed Notes 25 notes

up
154
carlosv775 at gmail dot com
9 years ago
In PHP 7.1 we can do the following:

<?php
    [$a, $b, $c] = ['a', 'b', 'c'];
?>

Before, we had to do:

<?php
    list($a, $b, $c) = ['a', 'b',  'c'];
?>
up
142
Rhamnia Mohamed
9 years ago
Since PHP 7.1, keys can be specified

exemple : 
<?php 
$array = ['locality' => 'Tunis', 'postal_code' => '1110'];

list('postal_code' => $zipCode, 'locality' => $locality) = $array;

print $zipCode; // will output 1110
print $locality; // will output Tunis
 ?>
up
98
grzeniufication
11 years ago
The example showing that:

$info = array('kawa', 'brązowa', 'kofeina');
list($a[0], $a[1], $a[2]) = $info;
var_dump($a);

outputs:
array(3) {
[2]=>
string(8) "kofeina"
[1]=>
string(5) "brązowa"
[0]=>
string(6) "kawa"
}

One thing to note here is that if you define the array earlier, e.g.:
$a = [0, 0, 0];

the indexes will be kept in the correct order:

array(3) {
  [0]=>
  string(4) "kawa"
  [1]=>
  string(8) "brązowa"
  [2]=>
  string(7) "kofeina"
}

Thought that it was worth mentioning.
up
9
xmgr2 at protonmail dot com
1 year ago
... and it also supports pushing items onto arrays.

I couldn't find any official documentation on this behavior, but it appears that you can "push" elements onto arrays directly using array destructuring assignments.

<?php
$users = [
    [1, 'Alice', 'alice@example.com', 'secret123'],
    [2, 'Bob', 'bob@example.com', 'pass456'],
    [3, 'Charlie', 'charlie@example.com', 'hunter678'],
];

$ids       = [];
$names     = [];
$emails    = [];
$passwords = [];

foreach ($users as $user) {
    [$ids[], $names[], $emails[], $passwords[]] = $user;
}
?>

For well-documented alternatives, consider using array_column(), which does quite the same:

<?php
$ids       = array_column($users, 0);
$names     = array_column($users, 1);
$emails    = array_column($users, 2);
$passwords = array_column($users, 3);
?>
up
77
megan at voices dot com
13 years ago
As noted, list() will give an error if the input array is too short. This can be avoided by array_merge()'ing in some default values. For example:

<?php
$parameter = 'name';
list( $a, $b ) = array_merge( explode( '=', $parameter ), array( true ) );
?>

However, you will have to array_merge with an array long enough to ensure there are enough elements (if $parameter is empty, the code above would still error).

An alternate approach would be to use array_pad on the array to ensure its length (if all the defaults you need to add are the same).

<?php
    $parameter = 'bob-12345';
    list( $name, $id, $fav_color, $age ) = array_pad( explode( '-', $parameter ), 4, '' );
    var_dump($name, $id, $fav_color, $age);
/* outputs
string(3) "bob"
string(5) "12345"
string(0) ""
string(0) ""
*/
?>
up
76
chris at chlab dot ch
13 years ago
The example states the following:
<?php
// list() doesn't work with strings
list($bar) = "abcde";
var_dump($bar); 
// output: NULL
?>

If the string is in a variable however, it seems using list() will treat the string as an array:
<?php
$string = "abcde";
list($foo) = $string;
var_dump($foo);
// output: string(1) "a"
?>
up
52
grzeniufication
9 years ago
<?php
/**
 * It seems you can skip listed values.
 * Here's an example to show what I mean.
 *
 * FYI works just as well with PHP 7.1 shorthand list syntax.
 * Tested against PHP 5.6.30, 7.1.5
 */
$a = [ 1, 2, 3, 4 ];

// this is quite normal use case for list
echo "Unpack all values\n";
list($v1, $v2, $v3, $v4) = $a;
echo "$v1, $v2, $v3, $v4\n";
unset($v1, $v2, $v3, $v4);

// this is what I mean:
echo "Skip middle\n";
list($v1, , , $v4) = $a;
echo "$v1, $v2, $v3, $v4\n";
unset($v1, $v2, $v3, $v4);

echo "Skip beginning\n";
list( , , $v3, $v4) = $a;
echo "$v1, $v2, $v3, $v4\n";
unset($v1, $v2, $v3, $v4);

echo "Skip end\n";
list($v1, $v2, , ) = $a;
echo "$v1, $v2, $v3, $v4\n";
unset($v1, $v2, $v3, $v4);

echo "Leave middle\n";
list( , $v2, $v3, ) = $a;
echo "$v1, $v2, $v3, $v4\n";
unset($v1, $v2, $v3, $v4);
up
37
pemapmodder1970 at gmail dot com
10 years ago
list() can be used with foreach

<?php
$array = [[1, 2], [3, 4], [5, 6]];

foreach($array as list($odd, $even)){
    echo "$odd is odd; $even is even", PHP_EOL;
}
?>

The output:
===
1 is odd; 2 is even
3 is odd; 4 is even
5 is odd; 6 is even
up
28
john at jbwalker dot com
12 years ago
The list construct seems to look for a sequential list of indexes rather taking elements in sequence. What that obscure statement means is that if you unset an element, list will not simply jump to the next element and assign that to the variable but will treat the missing element as a null or empty variable:

    $test = array("a","b","c","d");
    unset($test[1]);
    list($a,$b,$c)=$test;
    print "\$a='$a' \$b='$b' \$c='$c'<BR>";

results in:
$a='a' $b='' $c='c'

not:
$a='a' $b='c' $c='d'
up
7
nek dot dev at gmail dot com
3 years ago
It can be convenient to specify a default value in case an element is missing in the list. You can use operator + for this:

<?php
$someArray = ['color' => 'orange'];
['color' => $color, 'size' => $size] = $someArray + ['color' => null, 'size' => null];
?>

This will avoid the warning `Undefined array key "size"` you would encounter otherwise.
up
46
svennd
13 years ago
The list() definition won't throw an error if your array is longer then defined list. 
<?php

list($a, $b, $c) = array("a", "b", "c", "d");

var_dump($a); // a
var_dump($b); // b
var_dump($c); // c
?>
up
7
mark at manngo dot net
5 years ago
For PHP 7.1 on, the documentation states that integer and string keys can be mixed, but that elements with and without keys cannot. Here is an example, using data from getimagesize() with mixed keys:

<?php
    $data=[
        0=> 160,
        1 => 120,
        2 => 2,
        3 => 'width="160" height="120"',
        'mime' => 'image/jpeg'
    ];
    list(0=>$width,1=>$height,2=>$type,3=>$dimensions,'mime'=>$mime)=$data;