5.9 Holes in arraysThis is NOT the latest copy of this book; click here for the latest version.
Consider this script:
<?php
$array["a"] = "Foo";
$array["b"] = "";
$array["c"] = "Baz";
$array["d"] = "Wom";
print end($array);
while($val = prev($array)) {
print $val;
} ?>
As you can see, it is fairly similar to the previous example - it should iterate through an array in reverse, printing out values as it goes. However, there is a problem - the value at key "b" is empty, and it just so happens that both prev() and next() consider an empty value to be the sign that the end of the array has been reached, and so will return false, prematurely ending the while loop.
The way around this is the same way around the problems inherent to using for loops with arrays, and that is to use each() to properly iterate through your arrays, as each() will cope fine with empty variables and unknown keys. Therefore, the script should have been written as this:
<?php
$array["a"] = "Foo";
$array["b"] = "";
$array["c"] = "Baz";
$array["d"] = "Wom";
while (list($var, $val) = each($array)) {
print "$var is $val\n";
} ?>
|
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!
|