PHP 5.4.31 Released

list

(PHP 4, PHP 5)

listAssign variables as if they were an array

Description

array list ( mixed $var1 [, mixed $... ] )

Like array(), this is not really a function, but a language construct. list() is used to assign a list of variables in one operation.

Parameters

var1

A variable.

Return Values

Returns the assigned array.

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()

<table>
 <tr>
  <th>Employee name</th>
  <th>Salary</th>
 </tr>

<?php
$result 
$pdo->query("SELECT id, name, salary FROM employees");
while (list(
$id$name$salary) = $result->fetch(PDO::FETCH_NUM)) {
    echo 
" <tr>\n" .
          
"  <td><a href=\"info.php?id=$id\">$name</a></td>\n" .
          
"  <td>$salary</td>\n" .
          
" </tr>\n";
}

?>

</table>

Example #3 Using nested list()

<?php

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

var_dump($a$b$c);

?>
int(1)
int(2)
int(3)

Example #4 Using list() with array indices

<?php

$info 
= array('coffee''brown''caffeine');

list(
$a[0], $a[1], $a[2]) = $info;

var_dump($a);

?>

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

array(3) {
  [2]=>
  string(8) "caffeine"
  [1]=>
  string(5) "brown"
  [0]=>
  string(6) "coffee"
}

Notes

Warning

list() assigns the values starting with the right-most parameter. If you are using plain variables, you don't have to worry about this. But if you are using arrays with indices you usually expect the order of the indices in the array the same you wrote in the list() from left to right; which it isn't. It's assigned in the reverse order.

Warning

Modification of the array during list() execution (e.g. using list($a, $b) = $b) results in undefined behavior.

Note:

list() only works on numerical arrays and assumes the numerical indices start at 0.

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 add a note

User Contributed Notes 11 notes

up
31
chris at chlab dot ch
1 year 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
13
megan at voices dot com
10 months 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
18
svennd
1 year 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
0
John Galt
13 hours ago
This is one of very few times that I think it can make sense to use the error-suppression operator (@).

For example, a rudimentary API (assuming you're not using a framework) might work off of $_SERVER['PATH_INFO'] to run an operation.

For instance, a call to api.json.php/users might return an array of user IDs and a call to api.json.php/users/42 might return details about the user with the ID 42.

<?php
// ...
@list ($dataset, $identifier) = explode('/', $_SERVER['PATH_INFO']);
switch (
$dataset) {
    case
'users':
        if (isset(
$identifier)) {
            exit (
json_encode(get_user($identifier)));
        } else {
            exit (
json_encode(get_users()));
        }
   
// ...
}
// ...
up
0
john at jbwalker dot com
7 months 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
-1
Arne
11 months ago
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 ) );
?>
up
-3
srikanth at networthindia dot com
1 year ago
Note: list cannot assign array cast of object to variables straight away. first you need to convert the object to numeric indexed array.

ex:
list($a, $b, $d) = (array) $abc; // $abc is an object; this will not assign.
list($a, $b, $c) = array_values((array) $abc); // This will work.
up
-4
edam
5 months ago
This doesn't work on associative array.  For example:

    list( $a, $b, $c ) = array( 'a' => 'a', 'b' => 'b', 'c' => 'c' );
    PHP Notice:  Undefined offset: 2 in Command line code on line 1
    PHP Notice:  Undefined offset: 1 in Command line code on line 1
    PHP Notice:  Undefined offset: 0 in Command line code on line 1
up
-2
Achilles at thegreatwarrior dot com
1 year ago
Second, when you’re using the list() function, you must acknowledge each array element. You could not do this
list($weekday, $month) = $date;

But you can use empty values to ignore elements:
list ($weekday, , $month) = $date;
up
-5
Matt
1 year ago
You can't type check within the list() parameters:

list ( array $var1, $var2 ) = array ( array('one','two'), 'three');

generates a parse error, unexpected 'array'.
up
-2
Thanos K.
4 months ago
Also it seems that it doesn't work as expected with arrays with non numeric keys:

list($k, $l, $m) = array('a' => 'val1', 'b' => 'val2', 'c' => 'val3');

Gives empty variables..
To Top