O'Reilly logo

Upgrading to PHP 5 by Adam Trachtenberg

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 6. Iterators and SPL

Iteration is a key component of PHP programming. Whenever you loop through the elements of an array, the rows in a database, the files in a directory, or the lines of an HTML table, that’s iteration.

Iteration takes many forms in PHP, but the most popular two are foreach and while loops. For example:

foreach ($array as $key => $value) {
    // iterate through array elements
}

reset($array);
while (list($key, $value) = each($array)) {
    // iterate through array elements
}

Although both of these constructs solve the same problem, foreach is shorter and easier. Iteration using a while loop can also introduce subtle bugs into your code, like in this example:

// $path is valid and readable
$dir = opendir($path); 
while ($file = readdir($dir)) {
    print "$file\n";
}
closedir($dir);

This code opens and iterates through files in a directory. When there are no more files, readdir( ) returns false, the while ends, and the directory is closed. It works perfectly.

It works perfectly, that is, until someone places a file named 0 in the directory. Then, $file is set to 0, and the loop terminates early because while (0) evaluates as false. Oops.

The correct way to read files from a directory is as follows:

while (false !=  = ($file = readdir($dir))) {
    print "$file\n";
}

You need to do a strict equality check using the = = = operator. Even = = gives you the wrong results because PHP autoconverts $file from a string to a Boolean.

Since there’s no reason for you (or anyone else) ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required