note 97471 added to class.arrayiterator

From: Date: Wed, 21 Apr 2010 20:05:52 +0000
Subject: note 97471 added to class.arrayiterator
Groups: php.notes 
Request: Send a blank email to php-notes+get-168484@lists.php.net to get a copy of this message
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"; } ?> ---- Server IP: 69.147.83.197 Probable Submitter: 69.70.125.250 ---- Manual Page -- http://www.php.net/manual/en/class.arrayiterator.php Edit -- https://master.php.net/note/edit/97471 Del: integrated -- https://master.php.net/note/delete/97471/integrated Del: useless -- https://master.php.net/note/delete/97471/useless Del: bad code -- https://master.php.net/note/delete/97471/bad+code Del: spam -- https://master.php.net/note/delete/97471/spam Del: non-english -- https://master.php.net/note/delete/97471/non-english Del: in docs -- https://master.php.net/note/delete/97471/in+docs Del: other reasons-- https://master.php.net/note/delete/97471 Reject -- https://master.php.net/note/reject/97471 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#168484) next »