note 97471 deleted from class.arrayiterator by danbrown
| From: | danbrown@php.net | Date: | Wed, 21 Apr 2010 21:53:42 +0000 |
| Subject: | note 97471 deleted from class.arrayiterator by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-168486@lists.php.net to get a copy of this message | ||
Note Submitter: nate
----
Regarding the statement in the docs that says: "When you want to iterate over the same array
multiple times you need to instantiate ArrayObject and let it create ArrayIterator instances that
refer to it either by using foreach or by calling its getIterator() method manually."
This phrasing is very misleading, as it seems to indicate you cannot loop over an iterator object
more than once. This is FALSE! What the statement is attempting to warn of is the case where you
need to run *embedded* foreach loops over the same array/iterator.
You only need to use ArrayObject (or create multiple ArrayIterator objects) in the case where you
have *embedded* foreach loops over the same iterator/array. If you simply want to loop once over an
iterator, and then loop over the same iterator again, that is perfectly valid! Every invocation of
foreach() calls ArrayIterator's rewind() method, so looping multiple times over the same
iterator object is fine! You just can't embed them without using either ArrayObject or multiple
ArrayIterator.
<?php
// not embedded - perfectly valid, no problems
$ids = new ArrayIterator(range(1, 3));
foreach ($ids as $id1) { echo $id1, "\n"; }
foreach ($ids as $id2) { echo $id2, "\n"; }
// the docs are warning against this case.
// this won't do what you'd want it to do.
$ids = new ArrayIterator(range(1, 3));
foreach ($ids as $id1) {
foreach ($ids as $id2)
echo "${id1} : ${id2}\n";
}
// for embedded loops, you must instead do:
$ids = new ArrayObject(range(1, 3));
foreach ($ids as $id1) {
foreach ($ids as $id2)
echo "${id1} : ${id2}\n";
}
// which is the equivalent of this:
$ids = new ArrayObject(range(1, 3));
$ids1 = $ids->getIterator();
$ids2 = $ids->getIterator();
foreach ($ids1 as $id1) {
foreach ($ids2 as $id2)
echo "${id1} : ${id2}\n";
}
?>