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) ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access