Holes in arrays

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";
    }
?>

 

Next chapter: Arrays in strings >>

Previous chapter: The array cursor

Jump to:

 

Home: Table of Contents

Follow us on Identi.ca or Twitter

Username:   Password:
Create Account | About TuxRadar