php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #36070 foreach strange behaviour
Submitted: 2006-01-18 19:00 UTC Modified: 2007-06-04 22:09 UTC
From: dmtr79 at yahoo dot com Assigned:
Status: Closed Package: Feature/Change Request
PHP Version: 5.1.2 OS: Win32, Unix
Private report: No CVE-ID: None
 [2006-01-18 19:00 UTC] dmtr79 at yahoo dot com
Description:
------------
foreach seems to run in different ways when called globally and from a function. As it can be understood from the documentation, foreach shouldn't touch an original array and operate with its copy instead. But at least, one could expect its behaviour to be similar for the 2 cases described in code.

Reproduce code:
---------------
$array = array(1, 2);

function test() {
    global $array;
    foreach ($array as $a) foreach ($array as $b) echo "$a $b\n";
}

foreach ($array as $a) foreach ($array as $b) echo "$a $b\n";
echo "---\n";
test();

Expected result:
----------------
1 1
1 2
2 1
2 2
---
1 1
1 2
2 1
2 2

Actual result:
--------------
1 1
1 2
2 1
2 2
---
1 1
1 2


Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2007-06-04 12:47 UTC] michael at chunkycow dot com dot au
Howdy

This works fine for me on 5.2.1, will test on 5.2.3 when the server is updated.

output
1 1
1 2
2 1
2 2
---
1 1
1 2
2 1
2 2
 [2007-06-04 22:02 UTC] dmtr79 at yahoo dot com
That's working fine on 5.2.3. Thanks.
 
PHP Copyright © 2001-2025 The PHP Group
All rights reserved.
Last updated: Wed Dec 17 06:00:01 2025 UTC