php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #39477 foreach iterators have global scope
Submitted: 2006-11-12 11:26 UTC Modified: 2006-11-12 21:34 UTC
From: phpbug dot 20 dot antialias at spamgourmet dot com Assigned:
Status: Not a bug Package: Scripting Engine problem
PHP Version: 5.2.0 OS: Mac OS X v. 10.4.8
Private report: No CVE-ID: None
View Developer Edit
Welcome! If you don't have a Git account, you can't do anything here.
If you reported this bug, you can edit this bug over here.
(description)
Block user comment
Status: Assign to:
Package:
Bug Type:
Summary:
From: phpbug dot 20 dot antialias at spamgourmet dot com
New email:
PHP Version: OS:

 

 [2006-11-12 11:26 UTC] phpbug dot 20 dot antialias at spamgourmet dot com
Description:
------------
foreach iterators are bound to the scope of their arrays. This 
causes problems when a global array has been partially 
iterated through, and then inside the foreach, the same global 
array is iterated through again. The the inner foreach 
iterator effectively completes the iterations of the outer 
foreach iterator, yielding unexpected results.


Reproduce code:
---------------
$t = array("1", "2");
global $t;
foreach($t as $a) {
	foreach($t as $b) {
		echo $b;
	}
	echo $a;
	
}

Expected result:
----------------
1212

Actual result:
--------------
121

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2006-11-12 18:57 UTC] tony2001@php.net
Thank you for taking the time to write to us, but this is not
a bug. Please double-check the documentation available at
http://www.php.net/manual/ and the instructions on how to report
a bug at http://bugs.php.net/how-to-report.php

This is expected behaviour.
 [2006-11-12 21:06 UTC] phpbug dot 20 dot antialias at spamgourmet dot com
Alright... but I certianly wouldn't call this expected 
behaviour, I also couldn't find mention of this in the 
documentatinon.
 [2006-11-12 21:24 UTC] tony2001@php.net
http://www.php.net/manual/en/control-structures.foreach.php

The first form loops over the array given by array_expression. On each loop, the value of the current element is assigned to $value and ***the internal array pointer is advanced by one (so on the next loop, you'll be looking at the next element)***.
 [2006-11-12 21:34 UTC] phpbug dot 20 dot antialias at spamgourmet dot com
Thanks for the note, but is there a way to out the iterator on 
the stack without copying the entire array?
 
PHP Copyright © 2001-2025 The PHP Group
All rights reserved.
Last updated: Thu Jul 17 14:04:04 2025 UTC