Using list() in PHP

By: Andi, Stig and Derick Printer Friendly Format    

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.

 



Ask a Question



Most Viewed Articles (in PHP )

PHP file upload prompts authentication for anonymous users

unset() and empty() functions in PHP

Parent: child process exited with status 3221225477 -- Restarting

A Basic Example using PHP in AWS (Amazon Web Services)

Retrieve multiple rows from mysql and automatically create a table in PHP

Building a Video Sharing Site using PHP in AWS

Installing PHP with nginx-server under windows

Exception in module wampmanager.exe at 000F15A0 in Windows 8

Multiple File Upload in PHP using IFRAME

Password must include both numeric and alphabetic characters - Magento

Integers and Floating-Point Numbers in PHP

Reading .CSV file in PHP

How to fix: Warning: Visiting this site may harm your computer - domainameat.cc

Building PHP 5.x with Apache2 on SuSE Professional 9.1/9.2

Running different websites on different versions of PHP in Windows 2003 & IIS6 platform

Latest Articles (in PHP)

Comment on this tutorial