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

 

Want to learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: Arrays in strings >>

Previous chapter: The array cursor

Jump to:

 

Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.