Aryeh Gregor schreef:
On Mon, Aug 18, 2008 at 9:56 AM, Roan Kattouw roan.kattouw@home.nl wrote:
- If you're foreach()ing large arrays somewhere, try to use references: foreach($arr as $key => &$value) instead of foreach($arr as $key =>
$value) The latter makes a copy of $arr whereas the former doesn't. The former also allows you to change $value.
I looked this syntax up, and found this interestingly braindead gotcha that can occur when you do this. It's PHP bug 29992, of course marked BOGUS: http://bugs.php.net/bug.php?id=29992. Test case:
<?php $array = array( 1, 2, 3 ); foreach( $array as &$item ); foreach( $array as $item ); print_r( $array );
Outputs
Array ( [0] => 1 [1] => 2 [2] => 2 )
Clever, huh? Naturally it can't be changed because "people might use this for some weird reason". It's probably a good idea to either not use this syntax, or make sure you unset the variable after the loop:
foreach( $array as &$item ) { ... } unset( $item );
I know about this. But in my understanding, this bug can only occur when you mix non-referenced foreach() loops with referenced ones. If you use a reference at *every* loop (which is what Guy did), you should be fine.
Roan Kattouw (Catrope)