Re: bug when using foreach with references?
| From: | Derick Rethans | Date: | Mon, 16 Nov 2009 12:20:40 +0000 |
| Subject: | Re: bug when using foreach with references? | ||
| References: | 1 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-46053@lists.php.net to get a copy of this message | ||
On Mon, 16 Nov 2009, Mathieu Suen wrote:
> > > It would be arbitrarily breaking an explicit reference. I know I
> > > have code lying around that relies on multiple loops cleaning up a
> > > big complicated multi-level array. I do ugly things with
> > > references into that array and it would completely break if PHP
> > > magically deleted my references whether they are in the iterator
> > > or elsewhere.
> > >
> > > This has been this way for 6+ years and it is well documented on
> > > the http://php.net/foreach page. (see the big red
> > > warning box)
>
> Even though, that's a language issue. Why the hell in php the foreach
> do not capture the variable properly?
It *does* work properly. I will try to explain once more...
The following code:
<?php
$items = array('apple', 'banana', 'carrot');
print_r($items);
foreach ($items as &$item) { }
print_r($items);
foreach ($items as $item) { }
print_r($items);
?>
can be rolled out into:
<?php
$items = array('apple', 'banana', 'carrot');
print_r($items);
$item =& $items[0];
$item =& $items[1];
$item =& $items[2]; // line A
// $item now is the same var as $items[2];
print_r($items);
// $item still is the same as $items[2] as done in Line A, so $items[2] (and
// $item because it's the same variable) gets modified to 'apple'.
$item = $items[0];
// $item still is the same as $items[2] as done in Line A, so $items[2] (and
// $item because it's the same variable) gets modified to 'banana'.
$item = $items[1];
// $item still is the same as $items[2] as done in Line A, so $items[2] (and
// $item because it's the same variable) gets modified to 'banana' because it
// was assigned to this value in the line above.
$item = $items[2];
print_r($items);
?>
Does it makes sense now?
Derick
--
http://derickrethans.nl | http://ezcomponents.org | http://xdebug.org
twitter: @derickr