Using list() in PHP
By: Andi, Stig and Derick
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.
Archived Comments
Comment on this tutorial
- Data Science
- Android
- AJAX
- ASP.net
- C
- C++
- C#
- Cocoa
- Cloud Computing
- HTML5
- Java
- Javascript
- JSF
- JSP
- J2ME
- Java Beans
- EJB
- JDBC
- Linux
- Mac OS X
- iPhone
- MySQL
- Office 365
- Perl
- PHP
- Python
- Ruby
- VB.net
- Hibernate
- Struts
- SAP
- Trends
- Tech Reviews
- WebServices
- XML
- Certification
- Interview
categories
Related Tutorials
PHP code to write to a CSV file for Microsoft Applications
PHP code to write to a CSV file from MySQL query
PHP code to import from CSV file to MySQL
Password must include both numeric and alphabetic characters - Magento
Error: Length parameter must be greater than 0
PHP file upload prompts authentication for anonymous users
PHP file upload with IIS on windows XP/2000 etc
Multiple File Upload in PHP using IFRAME
Resume or Pause File Uploads in PHP
Exception in module wampmanager.exe at 000F15A0 in Windows 8