#21702 [Opn]: nested foreach on same array using reference fails

From: Date: Fri, 17 Jan 2003 08:23:32 +0000
Subject: #21702 [Opn]: nested foreach on same array using reference fails
References: 1  Groups: php.doc 
Request: Send a blank email to phpdoc+get-969350961@lists.php.net to get a copy of this message
ID: 21702 Updated by: moriyoshi@php.net Reported By: vdvo@vdvo.net Status: Open -Bug Type: Scripting Engine problem +Bug Type: Documentation problem -Operating System: Linux (but probably any) +Operating System: Any -PHP Version: 4.2.2 +PHP Version: Any New Comment: Actually this is a dupe of bug #14607, but this PR is much more concise than that, so I'm going to keep 14607 bogus and make this alive. Since foreach() uses "internal array pointer" and references are designed to share one such pointer, the deeper loop gets confused and your script never gives the expected result. Virtually the script can be rewritten as... <?php $a = array(1, 2); for ($ptr = 0; $ptr < count($a); $ptr++) { $b = $a[$ptr]; echo "outer: $b <br />\n"; for ($ptr = 0; $ptr < count($a); $ptr++) { $c = $a[$ptr]; echo "inner: $c <br />\n"; } } ?> Marking this as a documentation problem. Previous Comments: ------------------------------------------------------------------------ [2003-01-16 20:05:14] vdvo@vdvo.net Try this: <?php $a = array(1, 2); $ref =& $a; foreach ($ref as $b) { echo "outer: $b<br>\n"; foreach ($a as $c) echo "-- inner: $c<br>\n"; } ?> The output is: outer: 1 -- inner: 1 -- inner: 2 (i.e., the processing stops after the first iteration of the outer foreach). If I understand the docs well, the output should be: outer: 1 -- inner: 1 -- inner: 2 outer: 2 -- inner: 1 -- inner: 2 When you remove the ampersand from the assignment to $ref, it works as expected. The documentation is a bit unclear on this. It says "Also note that foreach operates on a copy of the specified array, not the array itself, therefore the array pointer is not modified as with the each() construct...", which leads me to believe that the sample code should work. But then it goes on to say: "However, the internal pointer of the original array *is* advanced with the processing of the array.", which seems to contradict the first quotation??? This is probably a dupe of bug #14607, but that one is closed as "bogus" and I can't reopen it. Also see bug #5052, which is similar but not quite, and it's closed. ------------------------------------------------------------------------ -- Edit this bug report at http://bugs.php.net/?id=21702&edit=1

« previous php.doc (#969350961) next »