Re: Unsetting loop variables at the end of the loop

From: Date: Sun, 27 Dec 2009 13:17:33 +0000
Subject: Re: Unsetting loop variables at the end of the loop
References: 1  Groups: php.internals 
Request: Send a blank email to internals+get-46524@lists.php.net to get a copy of this message
2009/12/27 Mike Wacker <mwacker@cornellsun.com>:
> PHP's documentation for foreach states that if you iterate by reference
> [foreach ($ii as &$i) ...], you should unset $i after the loop.  $i still
> points to the last element of the array - updating $i or reusing it will
> update the last element of the array.
>
> In short, why doesn't PHP automatically unset $i after the loop?  I can't
> think of too many cases where you would want to hold on to that reference
> after you exit the loop, but I can think of a lot of scenarios where a user
> could accidentally tamper the array by using $i in a different context later
> on (especially since loop variable names often are reused).

This is a bit of a FAQ, frankly. May I suggest reading this thread
from a couple of months ago:
http://marc.info/?l=php-internals&m=125617546815934&w=2.
There are
some more discussions both on the list and in the bug tracker if you
want to have a bit more of a dig into this.

The really, really short version is that it would break backward
compatibility to change it now, it's useful in some (admittedly
limited) cases, and it's not as though it's not well documented as
behaving that way.

Adam


Thread (20 messages)

« previous php.internals (#46524) next »