If you have an array and transverse it by calling next() or similar functions, you may eventually run off the end of the array. When this happens, not only can you not prev() back onto it - though end() works fine - there is no obvious way to tell if the array pointer is actually off the end.
ArrayIterator contains one solution, ArrayIterator::valid(), but lets pretend we don't want to bust out SPL. Yes, you could keep a counter also, but that is extra work we don't want to maintain.
It turns out there is one, and as far as I know only one, trick you can use. Arrays in PHP never have null keys. If you try, the null is coerced to an empty string. We can use this very useful fact to assert that is_null(key($myarray)) is true if and only if the array pointer is past the end of the array! Now we can do cool things like this:
function merry_go_round($array, $n) {
while ($n > 0) {
$currentElement = current($array);
echo $currentElement, ' ';
next($array);
if (is_null(key($array))) {
reset($array);
}
--$n;
}
}
// whee!!
merry_go_round(array(1, 2, 3), 20);
Of course, now we have to debate whether putting something nasty like is_null(key($array)) into our code is worth it. At least we should explain this intricacy of PHP with a comment and what we are really trying to do. But, why not just use SPL if it is clearer?
function merry_go_round($array, $n) {
$iterator = new ArrayIterator($array);
while ($n > 0) {
$currentElement = $iterator->current($array);
echo $currentElement, ' ';
$iterator->next($array);
if (!$iterator->valid()) {
$iterator->rewind($array);
}
--$n;
}
}
merry_go_round(array(1, 2, 3), 20);
Even after all the effort that went into being clever - and believe me there was quite a bit - it turns out that it was not worth it. Granted, if I did not learn the SPL solution only simultaneously with the clever solution I would have saved the time. If the path you are going down is confusing and cryptic, choose a different path. When you have no other paths to choose from, gripe about the language or something.
0 Responses to How to tell if your array pointer is past the end in PHP
Leave a Reply