ArrayIterator
is used to iterate over the elements of an array. In SPL, ArrayObject
has a built-in Iterator, which you can access using getIterator
function. You can use this object to iterate over any collection. Let's take a look at the example here:
<?php $fruits = array( "apple" => "yummy", "orange" => "ah ya, nice", "grape" => "wow, I love it!", "plum" => "nah, not me" ); $obj = new ArrayObject( $fruits ); $it = $obj->getIterator(); // How many items are we iterating over? echo "Iterating over: " . $obj->count() . " values\n"; // Iterate over the values in the ArrayObject: while( $it->valid() ) { echo $it->key() . "=" . $it->current() . "\n"; $it->next(); } ?>
This will output the following:
Iterating over: 4 values apple=yummy orange=ah ya, nice grape=wow, I love it! plum=nah, not me
However, an Iterator also implements the IteratorAggregator
interface so you can even use them in the foreach()
loop....