JavaScript Editor Javascript debugger     Website design 


Assign variables as if they were an array (PHP 4, PHP 5)
void list ( mixed varname, 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.


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

Example 312. list() examples


= array('coffee', 'brown', 'caffeine');

// Listing all the variables
list($drink, $color, $power) = $info;
"$drink is $color and $power makes it special.\n";

// Listing some of them
list($drink, , $power) = $info;
"$drink has $power.\n";

// Or let's skip to only the third one
list( , , $power) = $info;
"I need $power!\n";

// list() doesn't work with strings
list($bar) = "abcde";
var_dump($bar); // NULL

Example 313. An example use of list()

 <th>Employee name</th>


= mysql_query("SELECT id, name, salary FROM employees", $conn);
while (list(
$id, $name, $salary) = mysql_fetch_row($result)) {
" <tr>\n" .
"  <td><a href=\"info.php?id=$id\">$name</a></td>\n" .
"  <td>$salary</td>\n" .
" </tr>\n";




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.

Example 314. Using list() with array indices


= array('coffee', 'brown', 'caffeine');

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



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

array(3) {
 string(8) "caffeine"
 string(5) "brown"
 string(6) "coffee"

See also each(), array() and extract().