# Unsetting loop variables at the end of the loop

- Thread: https://externals.io/message/46523
- Original archive: https://news-web.php.net/php.internals/46523
- Started by Mike Wacker on 2009-12-27T12:56:22+00:00
- Messages: 20
- Reply by email to internals@lists.php.net
- More for agents: search with https://externals.io/search.md?q={query} · JSON API at https://externals.io/api · documentation at https://externals.io/llms.txt

---

## #46523 — Mike Wacker — 2009-12-27T12:56:22+00:00

URL: https://externals.io/message/46523#46523

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).

---

## #46524 — Adam Harvey — 2009-12-27T13:17:33+00:00

URL: https://externals.io/message/46523#46524 · In reply to: #46523

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

---

## #46526 — Mike Wacker — 2009-12-27T14:11:44+00:00

URL: https://externals.io/message/46523#46526 · In reply to: #46524

Adam Harvey wrote:
> 2009/12/27 Mike Wacker <mwacker@cornellsun.com>:
> > […]
> 
> 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.

Ah, so it seems that "reference" was the keyword I was missing in my 
search queries for the bug database.  It looks like I may have 
(re)opened a can of worms.

> The really, really short version is that it would break backward
> compatibility to change it now,

I would agree that if this did change, it would have to change in PHP 6 
and not 5.2/3.

> it's useful in some (admittedly limited) cases,

The main problem I see is that, like you said, these cases are limited. 
  If you really need to hold on to a reference after the loop, then why 
not make an explicit reference?

foreach ($ii as &$i) {
   $j =$ $i;
   // loop body
} // PHP implicitly unset()'s $i

In both this case and the status quo, someone has to add an extra line 
of code for every loop.  Since re-using a loop variable is a much more 
common use case, I feel that PHP should accommodate that use case and 
force people using references outside the loop to add the line of code 
instead.

> and it's not as though it's not well documented as behaving that way.
> 
> Adam

True, but it may not hurt to make the documentation more explicit to 
catch the most common use case.  You could add this clause: ", 
especially if $value is used elsewhere as a loop variable again." 
(Though should I maybe move this part into the doc newsgroup?)

---

## #46527 — Ferenc Kovacs — 2009-12-27T16:01:31+00:00

URL: https://externals.io/message/46523#46527 · In reply to: #46526

> Adam Harvey wrote:
> > […]
>
> Ah, so it seems that "reference" was the keyword I was missing in my search
> queries for the bug database.  It looks like I may have (re)opened a can of
> worms.
>
> > […]
>
> I would agree that if this did change, it would have to change in PHP 6 and
> not 5.2/3.
>
I would like to see this change in PHP6. :)
> > […]
>
> The main problem I see is that, like you said, these cases are limited.  If
> you really need to hold on to a reference after the loop, then why not make
> an explicit reference?
>
> foreach ($ii as &$i) {
>  $j =$ $i;
>  // loop body
> } // PHP implicitly unset()'s $i
>
> In both this case and the status quo, someone has to add an extra line of
> code for every loop.  Since re-using a loop variable is a much more common
> use case, I feel that PHP should accommodate that use case and force people
> using references outside the loop to add the line of code instead.
>
> > […]
>
> True, but it may not hurt to make the documentation more explicit to catch
> the most common use case.  You could add this clause: ", especially if
> $value is used elsewhere as a loop variable again." (Though should I maybe
> move this part into the doc newsgroup?)

---

## #46529 — Rasmus Lerdorf — 2009-12-27T16:05:00+00:00

URL: https://externals.io/message/46523#46529 · In reply to: #46527

We can't just randomly reset variables based on their scope in this one
specific case.  If we are going to "fix" this, it should be done by
introducing a way to do proper local scope variables.  Resetting a
reference simply because it is convenient in this one case would be
completely inconsistent.

-Rasmus

Ferenc Kovacs wrote:
> 
> > […]
> I would like to see this change in PHP6. :)
> > […]

---

## #46530 — Mike Wacker — 2009-12-27T18:46:21+00:00

URL: https://externals.io/message/46523#46530 · In reply to: #46529

Rasmus Lerdorf wrote:
> We can't just randomly reset variables based on their scope in this one
> specific case.  If we are going to "fix" this, it should be done by
> introducing a way to do proper local scope variables.  Resetting a
> reference simply because it is convenient in this one case would be
> completely inconsistent.
> 
> -Rasmus

I have some thoughts on this for PHP 6, but here's something else that 
might be worth looking into.

When you write [foreach ($ii as $i) ...], you usually expect that $i is 
not a reference variable (you would have used &$i otherwise).  However, 
PHP allows this even if $i is already a reference variable (e.g.: it was 
used as such in a previous loop).

Now look at this code:

function f(&$x) {
   echo $x;
}
$x = 1;
$args = array($x);
call_user_func_array('f', $args);

In PHP 5.3, this would trigger a warning and cause $x to be `NULL` inside 
of f because you mixed value and reference types in an improper way.

This foreach() issue is essentially being caused by a similar evil mix 
of reference and value types.  Perhaps [foreach ($ii as $i)] should 
trigger a warning if $i already exists as a reference variable.

---

## #46533 — jvlad — 2009-12-28T01:37:27+00:00

URL: https://externals.io/message/46523#46533 · In reply to: #46529

"Rasmus Lerdorf" <rasmus@lerdorf.com> wrote in message 
news:4B3785AC.2000507@lerdorf.com...
> We can't just randomly reset variables based on their scope in this one
> specific case.  If we are going to "fix" this, it should be done by
> introducing a way to do proper local scope variables.  Resetting a
> reference simply because it is convenient in this one case would be
> completely inconsistent.
>
> -Rasmus

Rasmus,
it's not required to do anything like that and I myself would be against any 
random resets,
but it's definitely not the case. There is nothing random and everything is 
well determinted.
As I see the problem, it would be sufficient to fix the FOREACH and make it 
working in the following way:
For example, say we have $a=array('apple', 'orange');
and iterate through $a values:
foreach($a as &$v) ...
as an initial step, $v MUST be assigned to the very first element of $a 
which 'apple'. It should be done regadless of the
value that might be assigned  to $v before (that's the first change)
On the next step, it will be advanced by one and assign $v to point to 
'orange'
On the next iteration, it MUST also be advanced by one, reach the End Of the 
Array, so it should assign `NULL` (or FALSE?) value to $v,
then finish the loop.

Isn't it what would work in a clearer way?

Evenmore, this change would make the foreach working more consistent with 
each()/next()/prev() - they return `FALSE` as soon as internal pointer
reaches either boundary of the array. Neither stick with last element, like 
foreach().

If you think current behaviour of foreach is useful, it's possible to 
introduce new setting in php.ini, say strict_foreach=ON that will break
BC, but make foreach working clearer.

-jv

---

## #46534 — Rasmus Lerdorf — 2009-12-28T01:57:00+00:00

URL: https://externals.io/message/46523#46534 · In reply to: #46533

jvlad wrote:
> "Rasmus Lerdorf" <rasmus@lerdorf.com> wrote in message 
> news:4B3785AC.2000507@lerdorf.com...
> > […]
> 
> Rasmus,
> it's not required to do anything like that and I myself would be against any 
> random resets,
> but it's definitely not the case. There is nothing random and everything is 
> well determinted.
> As I see the problem, it would be sufficient to fix the FOREACH and make it 
> working in the following way:
> For example, say we have $a=array('apple', 'orange');
> and iterate through $a values:
> foreach($a as &$v) ...
> as an initial step, $v MUST be assigned to the very first element of $a 
> which 'apple'. It should be done regadless of the
> value that might be assigned  to $v before (that's the first change)
> On the next step, it will be advanced by one and assign $v to point to 
> 'orange'
> On the next iteration, it MUST also be advanced by one, reach the End Of the 
> Array, so it should assign `NULL` (or FALSE?) value to $v,
> then finish the loop.
> 
> Isn't it what would work in a clearer way?
> 
> Evenmore, this change would make the foreach working more consistent with 
> each()/next()/prev() - they return `FALSE` as soon as internal pointer
> reaches either boundary of the array. Neither stick with last element, like 
> foreach().
> 
> If you think current behaviour of foreach is useful, it's possible to 
> introduce new setting in php.ini, say strict_foreach=ON that will break
> BC, but make foreach working clearer.

No chance.  No .ini settings, and I still maintain it is inconsistent.

So, if I write this:

$a = array(1);
$b = 0;
$c = &$b;
$c = $a[0];

Would you agree that $b should be 1 at this point?  If so, just because
I rewrite that code like this:

$a = array(1);
$b = 0;
$c = &$b;
foreach($a as $c);

Now you are arguing that $b should not be 1?

The two pieces of code are identical and since we do not have a block
scope and there is no syntax for explicitly indicating that $c is
somehow a different $c or that we should wipe out the $c that existed
before the foreach, I can see no sane reason to break the language for
this case.

And I don't see how your prev/next stuff has anything to do with this.

-Rasmus

---

## #46536 — jvlad — 2009-12-28T03:57:52+00:00

URL: https://externals.io/message/46523#46536 · In reply to: #46534

>
> No chance.  No .ini settings, and I still maintain it is inconsistent.
>
> So, if I write this:
>
> $a = array(1);
> $b = 0;
> $c = &$b;
> $c = $a[0];
>
> Would you agree that $b should be 1 at this point?  If so, just because
> I rewrite that code like this:
>
> $a = array(1);
> $b = 0;
> $c = &$b;
> foreach($a as $c);
>
> Now you are arguing that $b should not be 1?
>
> The two pieces of code are identical and since we do not have a block
> scope and there is no syntax for explicitly indicating that $c is
> somehow a different $c or that we should wipe out the $c that existed
> before the foreach, I can see no sane reason to break the language for
> this case.
>
> And I don't see how your prev/next stuff has anything to do with this.
>
> -Rasmus

Rasmus,


> $a = array(1);
> $b = 0;
> $c = &$b;
> foreach($a as $c);
> Now you are arguing that $b should not be 1?
> The two pieces of code are identical

It's just a nightmare example. I wonder have you ever see anything like this 
in real life?
Could you please let me see it too, for example in code.google.com?
If you cann't, what are you fighting for?
Interestingly, how many people will consider the code sample you 
demonstrated ugly...
How many sporadic problems were already created and will be created just 
beacause
of this unclear behavior of foreach?

> And I don't see how your prev/next stuff has anything to do with this.


Ok. What my stuff has to do with this is there:
If prev/next were consistent with foreach, they would return first/last 
element of the
array respectively as soon as they reached the boundary. But no! They return 
FALSE.

Please have a look at this page
http://www.php.net/manual/en/control-structures.foreach.php

It's where you can find the following:
------------------------------------------------------------------------------
You may have noticed that the following are functionally identical:
<?php
$arr = array("one", "two", "three");
reset($arr);
while (list(, $value) = each($arr)) {
    echo "Value: $value<br />\n";
}

foreach ($arr as $value) {
    echo "Value: $value<br />\n";
}
?>
------------------------------------------------------------------------------

why not to make while (list(, &$value) = each($arr)) identical to foreach 
($arr as &$value) ?
It would make the language more consistent.


Meanwhile I see that php core developers and Evangelist propose the way of 
evolving difficulties.
For example, I used split() for many many years. Now it throws a warning and 
it appears
that this function will be removed soon. I have to rewrite all my scripts 
and replace
this function with pcreXXXX one and make sure that pcre extension is 
built-in everywhere. So BC is
broken in an ugly and a very unpleasant way.
Many php developers who count on split() are simply ignored. Like me, they 
have to
spend their time for monkey work. Nobody asked for such changes! 
Difficulties are created in
a steady place.
On the other hand, people are experiencing difficulties with an important 
function (php operator)
because it's behaviour is unclear/unexpected/nonintuitive. They all are 
asking
for the change, but what? Right - they are ignored. Instead, new arguments 
and ugly samples
will demonstrate us php developers that we are just fools and have plenty of 
times.

Best regards,
JV

---

## #46537 — Rasmus Lerdorf — 2009-12-28T04:10:31+00:00

URL: https://externals.io/message/46523#46537 · In reply to: #46536

jvlad wrote:
> > […]
> 
> It's just a nightmare example. I wonder have you ever see anything like this 
> in real life?
> Could you please let me see it too, for example in code.google.com?
> If you cann't, what are you fighting for?
> Interestingly, how many people will consider the code sample you 
> demonstrated ugly...
> How many sporadic problems were already created and will be created just 
> beacause
> of this unclear behavior of foreach?

It isn't unclear.  It is perfectly consistent.  Whether it is ugly or
not is irrelevant.

> > […]
> 
> 
> Ok. What my stuff has to do with this is there:
> If prev/next were consistent with foreach, they would return first/last 
> element of the
> array respectively as soon as they reached the boundary. But no! They return 
> FALSE.

Which has nothing to do with the question at hand here.  We are talking
about breaking any reference in the variables used in the loop
construct.  We are not talking about any other behaviour here.

-Rasmus

---

## #46538 — Rasmus Lerdorf — 2009-12-28T05:59:00+00:00

URL: https://externals.io/message/46523#46538 · In reply to: #46536

jvlad wrote:
> Meanwhile I see that php core developers and Evangelist propose the way of 
> evolving difficulties.
> For example, I used split() for many many years. Now it throws a warning and 
> it appears
> that this function will be removed soon. I have to rewrite all my scripts 
> and replace
> this function with pcreXXXX one and make sure that pcre extension is 
> built-in everywhere. So BC is
> broken in an ugly and a very unpleasant way.
> Many php developers who count on split() are simply ignored. Like me, they 
> have to
> spend their time for monkey work. Nobody asked for such changes! 

Do you think we are deprecating split() just for fun?  We are letting
you know that you need to start thinking about migrating your code away
from non-Unicode aware functions like ereg() and split().  The Web is
going entirely Unicode as is PHP 6 and these functions simply do not
support Unicode strings.  `preg_split()` is a decent substitute and you
should be able to convert to it with only minor changes in your regex.

And this has nothing to do with this thread.  Please keep your rants at
least somewhat on topic.

-Rasmus

---

## #46546 — jvlad — 2009-12-28T10:44:37+00:00

URL: https://externals.io/message/46523#46546 · In reply to: #46537

> jvlad wrote:
> > […]
>
> It isn't unclear.  It is perfectly consistent.  Whether it is ugly or
> not is irrelevant.

Even though you can kill somebody using hammer, does it mean that it _is_ 
the feature to
be preserved in all future versions of the hammer?
Also, you didn't answer why another function that is WIDELY used, is going 
to hell.
Why don't you defend its features which go to hell with this function? Why 
don't you
defent the language BC in this case? What does make your position so 
selective?
Why a useless and harmful (yes it's harmful according to so many posts) 
feature is preserved
while uselfull and needed function is going away?


>
> > […]
>
> Which has nothing to do with the question at hand here.  We are talking
> about breaking any reference in the variables used in the loop
> construct.  We are not talking about any other behaviour here.


Please have a look at this page
http://www.php.net/manual/en/control-structures.foreach.php
It's where you can find the following:
------------------------------------------------------------------------------
You may have noticed that the following are functionally identical:
<?php
$arr = array("one", "two", "three");
reset($arr);
while (list(, $value) = each($arr)) {
    echo "Value: $value<br />\n";
}

foreach ($arr as $value) {
    echo "Value: $value<br />\n";
}
?>
------------------------------------------------------------------------------

I checked and it appears that they are not identical, quite the opposite, 
they expose the
difference I mentioned before.
Each() assigns `NULL` to the value after the array pointer reached end.
ForEach() stays with last element in this case:
compare the output:
<?php
$arr = array("one", "two", "three");
reset($arr);
while (list(, $value) = each($arr)) {
    echo "Value: $value<br />\n";
}
var_dump($value);
?>

<?php
$arr = array("one", "two", "three");
foreach ($arr as $value) {
    echo "Value: $value<br />\n";
}
var_dump($value);
?>

-jv

---

## #46547 — jvlad — 2009-12-28T10:58:09+00:00

URL: https://externals.io/message/46523#46547 · In reply to: #46538

> Do you think we are deprecating split() just for fun?

Yes, exactly. It's just made for _fun_ by core developers and brought 
headache
to people developing in php.

> We are letting you know that you need to start thinking about migrating
> your code away from non-Unicode aware functions like ereg() and split().

Well, this filled up my php logs with some million records telling me this!
Do you think it's safer to keep thinking and have an opportunity to miss 
anything
dangerous in the logs just becase they are flooded.

> The Web is going entirely Unicode as is PHP 6 and these functions simply 
> do not
> support Unicode strings.  `preg_split()` is a decent substitute and you
> should be able to convert to it with only minor changes in your regex.

If these changes are minor, why don't you provide a version of split for 
php6 that will make them
on the fly? Why don't you consider the other scenarios that would maintain 
the language BC?

>
> And this has nothing to do with this thread.  Please keep your rants at
> least somewhat on topic.

It has direct relation to this thread because it's all about the policy of 
the changes in the language.
Some pain changes are already done, some painless are not allowed.
Whould you please make your position more public and clearer?

-jv

---

## #46551 — Ferenc Kovacs — 2009-12-28T12:39:50+00:00

URL: https://externals.io/message/46523#46551 · In reply to: #46547

> > […]
>
> Yes, exactly. It's just made for _fun_ by core developers and brought
> headache
> to people developing in php.
>
> > […]
>
> Well, this filled up my php logs with some million records telling me this!
> Do you think it's safer to keep thinking and have an opportunity to miss
> anything
> dangerous in the logs just becase they are flooded.
>
> > […]
>
> If these changes are minor, why don't you provide a version of split for
> php6 that will make them
> on the fly? Why don't you consider the other scenarios that would maintain
> the language BC?
>
> > […]
>
> It has direct relation to this thread because it's all about the policy of
> the changes in the language.
> Some pain changes are already done, some painless are not allowed.
> Whould you please make your position more public and clearer?
>
as far as I see, the changes depends on how many work has to be done,
to preserve something.
posix functions like split, and so could have been modified to work
with the unicode strings, but nobody cared enough.

now this request is easier to leave this way, because this scenario
needs zero work against the proposed solutions.

but hey: patches are welcome!
:/

Tyrael
> -jv

---

## #46552 — Derick Rethans — 2009-12-28T14:19:58+00:00

URL: https://externals.io/message/46523#46552 · In reply to: #46547

> > […]
> 
> Well, this filled up my php logs with some million records telling me 
> this! Do you think it's safer to keep thinking and have an opportunity 
> to miss anything dangerous in the logs just becase they are flooded.

Bitching about upgrading and things not working is not going to get you 
any karma. We release release-candidates for a reason, and blindly 
upgrading is unprofessional.

Derick

-- 
http://derickrethans.nl | http://ezcomponents.org | http://xdebug.org
twitter: @derickr

---

## #46553 — jvlad — 2009-12-28T15:05:42+00:00

URL: https://externals.io/message/46523#46553 · In reply to: #46552

> > […]
>
> Bitching about upgrading and things not working is not going to get you
> any karma. We release release-candidates for a reason, and blindly
> upgrading is unprofessional.

Derick,
No need to upgrade.
If you write any line in php that other people are interested to run,
you'll see it soon, that different people use different versions of php.
If your code relies on split(), you'll get very good feedback from some of 
them.
FYI: I didn't say anything like what you answered to.

---

## #46554 — jvlad — 2009-12-28T15:07:10+00:00

URL: https://externals.io/message/46523#46554 · In reply to: #46551

> as far as I see, the changes depends on how many work has to be done,
> to preserve something.

I see the same.

> posix functions like split, and so could have been modified to work
> with the unicode strings, but nobody cared enough.

Because this work is not in the TODO (milestones).

-jv

---

## #46556 — Tjerk Meesters — 2009-12-28T15:39:53+00:00

URL: https://externals.io/message/46523#46556 · In reply to: #46551

> 
> > […]
> as far as I see, the changes depends on how many work has to be done,
> to preserve something.
> posix functions like split, and so could have been modified to work
> with the unicode strings, but nobody cared enough.
>
Besides, nobody's forcing you to "upgrade" to php6. Pragmatism applied  
I would just retrofit split() to `preg_split()` in userland whenever not  
defined, since by right pcre cannot be disabled ;-)
> now this request is easier to leave this way, because this scenario
> needs zero work against the proposed solutions.
>
> but hey: patches are welcome!
> :/
>
> Tyrael
> > […]

---

## #46557 — Ferenc Kovacs — 2009-12-28T15:44:27+00:00

URL: https://externals.io/message/46523#46557 · In reply to: #46554

> > […]
>
> I see the same.
>
> > […]
>
> Because this work is not in the TODO (milestones).
>
yeah, not anymore, but there was a thread about this on the internals
that (A. make the posix unicode-ready, B, use the preg extension for
the ereg functions transparently), but nobody cared enough.
The whole release of the 5.3 was a little bit mess.
There was a lot of feature, some of them wasn't ready for release, but
it was too much finished stuff to let this slide, and we are much
further from PHP6 than 5 years ago...
So its kinda funny, that some stuff had to die, because some stuff,
that wasnt even finished would be incompatible with.
Sorry for my english.

Tyrael
> -jv

---

## #46558 — Ferenc Kovacs — 2009-12-28T15:48:41+00:00

URL: https://externals.io/message/46523#46558 · In reply to: #46556

On Mon, Dec 28, 2009 at 4:39 PM, Tjerk Meesters
<tjerk.meesters@gmail.com> wrote:
> 
>
> > […]
> Besides, nobody's forcing you to "upgrade" to php6. Pragmatism applied I
> would just retrofit split() to `preg_split()` in userland whenever not
> defined, since by right pcre cannot be disabled ;-)
we are talking about php5.3. It got deprecated in that version, and
there were emails on the list about discontinuing the 5.2 branch as
soon as the 5.3 is ~stable.

Tyrael
> > […]
