Hudzilla.org - the homepage of Paul Hudson
Contents > Arrays Wish List | Report Bug | About Me ]

5.3     The three ways of iterating through arrays: list(), each(), and foreach loops

This is NOT the latest copy of this book; click here for the latest version.

void list ( mixed ...)

array each ( array input)

If you do not specify a key, as in the first example, PHP will just assign incrementing numbers. However, these numbers cannot be guaranteed to exist within the array in any given order, or even to exist at all - they are just key values themselves. For example, an array may have keys 0, 1, 2, 5, 3, 6, 7. That is, it can have its keys out of order or entirely missing. As a result, code like this should generally be avoided:

<?php
    
for ($i = 0; $i < count($array); ++$i) {
        print
$array[$i];
    }
?>

However, there is a quick and easy way to accomplish the same thing:

<?php
    
while (list($var, $val) = each($array)) {
        print
"$var is $val\n";
    }
?>

List() is a function that does the opposite of array() - it takes an array, and converts it into individual variables. Each() takes an array as its parameter, and returns the current key and value in that array before advancing the array cursor. "Array cursor" is the technical term for the element of an array that is currently being read. All arrays have a cursor, and you can freely move it around - it is used in the while loop above, where we need to iterate through an array. To start with, each() will return the first element, then the second element, then the third, and so on, until it finds there are no elements left, in which case it will return false and end the loop.

The meaning of that first line is "get the current element in the array, and assign its key to $var and its value to $val, then advance the array cursor. There is a lot more detail on array cursors later.

The third, final, and perhaps easiest way to iterate through an array is using a foreach loop, which itself has two versions. The easiest way to use foreach looks like this:

foreach($array as $val) {
    print
$val;
}

Here the array $array is looped through and its values are extracted into $val. In this situation, the array keys are ignored completely, which usually makes most sense when they have been auto-generated (i.e. 0, 1, 2, 3, etc).

The second way to use foreach does allow you to extract keys, and looks like this:

foreach ($array as $key => $val) {
    print
"$key = $val\n";
}

Generally speaking, using foreach loops is the most optimised way to loop through an array, and is also the easiest to read. In practice, however, you will find foreach loops and list()/each() loops in about equal proportions, despite the latter option being slower. The key difference between the two is that foreach automatically starts at the front of the array, whereas list()/each() does not.





<< 5.2 Associative arrays   5.4 The array operator >>
Table of Contents
Want to see this stuff in print? PHP in a Nutshell takes the core topics covered here, adds in thousands of edits from the editorial team and myself, and combines them to make an unbeatable reference for PHP programmers at all levels.



My latest book has hundreds more tips on how to use PHP, Apache, and MySQL, plus Perl, Python, shell scripts, performance tuning, and more!



Top-right shadow
 
Bottom-left shadow Bottom shadow

Comments from other readers
GamingG@firefoxowns.com - 29 Aug 2008

list() is not a true function, but a language construct. list() is a bit hard to explain, so perhaps I can show you with code:

list($one, $two, $three) = array("one", "two", "three");

$one will be "one", $two will be "two", etc. You can also skip elements, like:

list($one, , $three) = array("one", "two", "three);

Now $one is "one" and $three is "three", but the array value of "two" is discarded.

each() returns an array containing the key at index 0 and the value at index 1, so list() will assign the key to the first variable, and the value to the second. If the array is at its end, however, each() will return false, and list() will assign NULL to all of the variables. Any assignment statement returns the value assigned, so the list($key, $value) = each($array) statement would always return the return value of each(). If each() returns false, the while loop stops.

Ask - 29 Aug 2008

I have difficulties understanding the list() function. It

'..does the opposite of array() - it takes an array, and converts it into individual variables.'

But its arguments here are variables for key and value, not the array itself. Does the statement "while (list($var, $val) = each($array))" function as follows:

1) each($array) returns an array with just ONE element in it: the current cursor key and value.
2) this resulting single-element array is put into the list() function, which passes the cursor key and value onto the variables $var and $val.
3) after executing the each() function, the array cursor is advanced one position.
4) as long as "(list($var, $val) = each($array))" evaluates True (which is as long as the array cursor hasn't reached the end of the array) the while loop will run. But how does this work? List() returns void, each() an array.

And what happens when I execute "list($var, $val) = $array"? Does this put all key/value information from $array in the $var and $val variables, rendering them arrays?

Perhaps I should take this for granted, but I'd like to get to the bottom of this.

Can someone help me out here. Thanks!

deathgod - 29 Aug 2008

To randolph

the source of your confusion lies in not understanding the count() function. In that example there, the count($array) evaluates to the number 3. So the FOR is evaluated to this:
for ($i = 0;$i < 3; $i++){
blablabla;
}

This page is a little hard but if you dont understand the above then maybe its the FOR statements you are having a problem with

lazymoon.org - 29 Aug 2008

According to PHP4 Benchmarks by Web Related Talks (http://byster.net/?page_id=36#a1), foreach loop is the fastest of the loops.

Randolph - 29 Aug 2008

I didn`t understand. Consider the following:

<?php

$myarray = array("bob","steve","jon");

for ($i = 0;$i < count($myarray); $i++) {
print "Element: $array[$i]\n";
}

?>

Should I avoid this kind of construction and use list/each/foreach instead?

Jonno - 29 Aug 2008

list()/each() is actually quicker to execute. The main reason for this is that with the foreach() loop works by creating a duplication of the array in memory and all assignments are made through that.

Performance wise, this duplication requires a lot of both CPU and memory resources that could cook up lots of problems particularly when handling larger arrays.

An intresting page benchmarking this can be found here:

http://www.php.lt/benchmark/phpbench.php

Jonno



Add comment
Please note that by posting a comment here you are committing it to the public domain. This is important so that others can make use of your code themselves, and also so that I can incorporate helpful notes directly into the main text. Comments are limited to 2000 characters in length.

If you are reporting an error in the content, please tell me directly.

Your name/email address:
Your comment:
 
Now, in order to verify that you're a real person, please answer this simple question: what is seven plus four?
The answer is:
(please write in
numbers, eg 19)


Top-right shadow
 
Bottom-left shadow Bottom shadow