In our second article on the standard PHP library, David Fells explains the new Arrray object, introduces Iterators and the ArrayIterator, and discusses some practical examples of their usage. This article assumes a knowledge of how Exceptions work in PHP 5.
The following code snippet shows a simple example of creating an ArrayObject object and an ArrayIterator object, then traversing the iterator using the three most common control structures for iteration - foreach, for and while.
$myArray = new ArrayObject();
$myArray->append('a');
$myArray->append('b');
$myArray->append('c');
$i = $myArray->getIterator();
foreach ($i as $item) {
print $item.'<br />';
}
$i->rewind();
for (; $i->valid(); $i->next()) {
print $i->current().'<br />';
}
$i->rewind();
while ($i->valid()) {
print $i->current().'<br />';
$i->next();
}
The first line of this example creates an ArrayObject object and the next three lines call the append() method to add "a", "b" and "c" to the array. The fifth line gets an ArrayIterator object from the ArrayObject by calling the getIterator() method. Once we have the iterator, we are free to traverse the object in a number of different ways. The first method shown uses the foreach() control structure. Note that after traversing the iterator, we must reset it to its initial position with the rewind() method.
The second method demonstrates using an iterator with a for loop. Note that we do not need any initialization condition in the loop, but we could move the call to rewind() after the previous iteration to the for loop if desired. The condition section of the loop calls the valid() method of our iterator which returns true if more elements of the array exist after our current position and false if not. For our change section, we call the next() method which advances the iterator to the next element it contains.
The last method uses a while loop. Our condition, like the for loop above, uses the valid() method. In this example, however, we call next() after working with our data.