Page 1 of 1

foreach against global array not resetting

Posted: Thu Dec 10, 2009 12:30 pm
by jrisken
On a server running PHP 4.4, the code below prints

1123

But if I remove the global declaration it prints

1123
2123
3123

Does anyone know if this is a bug, or if it was a feature changed in later version of PHP (A server running PHP 5.2.11 gives the latter result set with or without the global declaration.

Code: Select all

 
    global $testArray;
    $testArray=array("1","2","3"); 
    print "<br>Program starts<br>";
    foreach($testArray as $k=>$v)
    {
        print "<br>Outer $v -> inner";
        foreach($testArray as $kinner=>$vinner)
        {
            print $vinner;
        }
    }       
    print  "<br><br>Program Ends";
 

Re: foreach against global array not resetting

Posted: Thu Dec 10, 2009 12:49 pm
by AbraCadaver
http://us3.php.net/manual/en/control-st ... oreach.php
Note: Unless the array is referenced, foreach operates on a copy of the specified array and not the array itself. foreach has some side effects on the array pointer. Don't rely on the array pointer during or after the foreach without resetting it.

Also: http://bugs.php.net/bug.php?id=40705

Re: foreach against global array not resetting

Posted: Thu Dec 10, 2009 1:03 pm
by jrisken
That's helpful. But can you say more?

For example, is the only safe coding to make a copy of the array and do the inner foreach against that copy?

And: If I were coding only for 5.2 and above, would I need to take that precaution? That is, is the current behavior now considered stable and correct?

Re: foreach against global array not resetting

Posted: Thu Dec 10, 2009 1:24 pm
by AbraCadaver
jrisken wrote:That's helpful. But can you say more?

For example, is the only safe coding to make a copy of the array and do the inner foreach against that copy?

And: If I were coding only for 5.2 and above, would I need to take that precaution? That is, is the current behavior now considered stable and correct?
I would say to make a copy of it. The behavior changed between versions and may change again, and all you will get from the PHP devs is: foreach has some side effects on the array pointer. Don't rely on the array pointer during or after the foreach without resetting it. So, do not rely on the behavior being consistent.

Re: foreach against global array not resetting

Posted: Thu Dec 10, 2009 2:08 pm
by jrisken
You have been very helpful. Thanks.