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:
$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.
$fruits = array(
"apple" => "yummy",
"orange" => "ah ya, nice",
"grape" => "wow, I love it!",
"plum" => "nah, not me"
);
$obj = new ArrayObject( $fruits );
Standard PHP Library
[ 148 ]
$it = $obj->getIterator();
// How many items are we iterating over?
echo "Iterating over: " . $obj->count() .
Pages:
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165