|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2004-08-15 12:37 UTC] swalk at prp dot physik dot tu-darmstadt dot de
Description:
------------
When using foreach with an array that has been referenced before, it behaves oddly if you re-set the variable inside the loop - it loses the array it originally worked on. That doesn't happen if you leave the line creating the reference out.
Reproduce code:
---------------
<?php
$a = array(1,2,3);
$b =& $a; // this line causes the bug
// $a =& $a; does it too
foreach($a as $v) {
print "$v\n";
$a = "foo";
}
Expected result:
----------------
1
2
3
Actual result:
--------------
1
Warning: Invalid argument supplied for foreach() in /home/et/test.php on line 4
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Sat Oct 25 13:00:01 2025 UTC |
I'm afraid that is caused just by the line $a = "foo"; which re-sets the $a variable to string, so it is no longer an array and can't be enumerated by next loop...Care to explain why doing $a =& $a; before the loop should affect the behaviour? In my (and some others whom i talked to) opinion that behaviour is bogus. And if it does make sense, it should be reflected in the documentation (where it isn't), because this caused someone an error with a high WTF factor in an application. Example: foreach ($_SESSION['something'] as $foo) { do_something; $something = "foo"; do_something_else; } Breaks on a server with register_globals on.I don't use register globals. But there are lots of servers which do. 1st, you're contradicting the Documentation, which clearly states that the array should be copied: "Note: Also note that foreach operates on a copy of the specified array and not the array itself." 2nd, you didn't specify the difference between using a reference variable and a normal variable. If you do foreach($array as $v) { array_push($array, 0); } modifying the array, it doesn't affect the loop. By your reasoning, it should? Please don't bogus it again, because it is either a problem with the documentation or with the implementation.