Using list() in PHP

By: Andi, Stig and Derick Viewed: 153177 times    

The list() construct is a way of assigning multiple array offsets to multiple variables in one statement:

list($var1, $var2, ...) = $array;

The first variable in the list is assigned the array value at offset 0, the second is assigned offset 1, and so on. Therefore, the list() construct translates into the following series of PHP statements:

$var1 = $array[0];

$var2 = $array[1];

...

The indexes 0 and 1 returned by each() are used by the list() construct. You can probably already guess how the combination of list() and each() work.

Consider the highlighted line from the previous $players traversal example:

$players = array("John", "Barbara", "Bill", "Nancy");

reset($players);

while (list($key, $val) = each($players)) {

print "#$key = $val\n";

}

What happens in the boldfaced line is that during every loop iteration, each() returns the current position’s key/value pair array, which, when examined with print_r(), is the following array:

Array

(

[1] => John

[value] => John

[0] => 0

[key] => 0

)

Then, the list() construct assigns the array’s offset 0 to $key and offset 1 to $val.

 

Most Viewed Articles (in PHP )

Latest Articles (in PHP)

Comment on this tutorial