note 66000 deleted from control-structures.foreach by danbrown
| From: | danbrown@php.net | Date: | Tue, 28 Apr 2009 13:05:54 +0000 |
| Subject: | note 66000 deleted from control-structures.foreach by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-153910@lists.php.net to get a copy of this message | ||
Note Submitter: php at kormoc dot com
----
With foreach and references, there is a super easy way to corrupt your data
see this test script:
<?php
$array = array(1,2,3);
foreach( $array as &$item );
foreach( $array as $item );
print_r( $array );
?>
You would imagine that it would have 1,2,3 but in reality, it outputs 1,2,2
The issue is that $item is a pointer to the last array value, and exists outside of the scope of the
foreach, so the second foreach overwrites the value. If you would check what it gets set to in the
second foreach loop, you would see that it gets set to 1 and then 2 and then 2 again.
This has already been filed as a bug, see:
http://bugs.php.net/bug.php?id=29992
but php developers seem to think that it's expected behaviour and *good* behaviour, so
it's doubtful that it will change anytime soon. This is a really bad gotcha, so watch out.