41
56
”
Arrays
Array Iteration
Iterationis probably one of the most commonoperations you will perform with ar-
rays—besides creating them, of course. Unlike what happens in other languages,
where arrays are all enumerative and contiguous,PHP’s arrays require a set offunc-
tionality that matches their flexibility, because “normal” looping structures cannot
cope with the factthat array keys do notneed to be continuous—or,for that matter,
enumerative. Consider, for example, this simple array:
$a = array (’a’ => 10, 10 => 20, ’c’ => 30);
Itis clear thatnone of the looping structures we have examined sofar will allowyou
to cycle through the elements of the array—unless, that is, you happen to know ex-
actly whatitskeys are, which is,at best, a severe limitation on your abilityto manip-
ulate a generic array.
TheArray Pointer
Each array has a pointer that indicates the “current” element of an array in an it-
eration. The pointer is used by a number of different constructs, but can only be
manipulated through a set offunctions and does notaffect your ability to access in-
dividual elements of an array, nor is it affected by most “normal” array operations.
Thepointer is,infact,ahandywayofmaintainingtheiterativestate ofanarraywith-
out needing anexternal variable todo the job for us.
The most direct way of manipulating the pointer of an array is by using a series
of functions designed specifically for this purpose. Upon starting an iteration over
an array, the first step is usually to reset the pointer to its initial position using the
reset()
function; after that, we can move forward or backwards by one position by
using
prev()
and
next()
respectively. At any given point, we can access the value of
the current elementusing
current()
and its key using
key()
.Here’san example:
$array = array(’foo’ => ’bar’, ’baz’, ’bat’ => 2);
function displayArray($array) {
reset($array);
while (key($array) !== null) {