On 1/7/2012 4:44 PM, Stephen wrote:
On 12-01-07 07:30 PM, Tim Behrendsen wrote:

When you use an ampersand on the variable, that creates a reference to the array elements, allowing you to potentially change the array elements themselves (which I'm not doing here).

http://www.php.net/manual/en/control-structures.foreach.php

I do notice in the manual that it says, "Reference of a $value and the last array element remain even after the foreach loop. It is recommended to destroy it by unset()." But that doesn't really explain why it contaminates the next foreach loop in such an odd way. You would think that the $row in the second loop would be assigned a non-reference value.

Tim

Tim,

You are using the &$variable in an unintended (by PHP designers), and I suggest undefined manner.

So the outcome cannot, but definition be explained.

Was this intended, and what were you trying to accomplish?

Stephen

In the real code, I just happen to use the same variable name first as a reference, and then as a normal non-reference, and was getting the mysterious duplicate rows.

I think I'm using everything in a completely reasonable way; the second foreach is reassigning the loop variable. Nothing that comes before using that variable ought to cause undefined behavior. The warning in the manual is about using the loop variable as a reference after exiting the loop, but I'm not doing that. I'm reassigning it, exactly as if I just decided to do a straight assignment of "$row"....

Ah ha, wait a minute, that's the key. OK, this is making more sense.

The first loop is leaving a reference to the final element. But then the second foreach is doing a straight assignment to the $row variable, but $row is a reference to the final element. So the foreach is assigning its iterated value to the final element of the array, instead of a normal variable.

OK, I understand the logic now. The world now makes sense. The moral is always unset the iterator variable when doing foreach with a reference, like the manual says. :)

Thanks for everyone's help.

Tim

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to