note 42576 added to control-structures.foreach
| From: | turadg at berkeley dot edu | Date: | Fri, 21 May 2004 21:19:25 +0000 |
| Subject: | note 42576 added to control-structures.foreach | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-69926@lists.php.net to get a copy of this message | ||
The documentation above says "the internal pointer of the original array is advanced with the
processing of the array".
In my experience, it's more complicated than that. Maybe it's a bug in 4.3.2 that
I'm using.
If the array variable is created by =& assignment, then it works as described. You can use
current() within the loop to see the next element.
If the array variable is created by an = assignment, the foreach() doesn't advance the pointer.
Instead you must use next() within the loop to peek ahead.
The code below demonstrates. On my system, the output is the same for both blocks, though one uses
next() and the other current().
$originalArray = array("first", "second", "third", "fourth",
"fifth");
print "the array:\n";
print_r($originalArray);
print "\noriginalArray with next():\n";
foreach ($originalArray as $step) {
$afterThis = next($originalArray);
print "$step,$afterThis\n";
}
$aliasArray =& $originalArray;
print "\naliasArray with current():\n";
foreach ($aliasArray as $step) {
$afterThis = current($aliasArray);
print "$step,$afterThis\n";
}
----
Manual Page -- http://www.php.net/manual/en/control-structures.foreach.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+42576
Delete -- http://master.php.net/manage/user-notes.php?action=delete+42576&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+42576&report=yes
Search -- http://master.php.net/manage/user-notes.php