Page 1 of 1

FTW

Posted: Tue Jul 07, 2009 10:56 am
by ubax

Code: Select all

 
<?php
$a = array('a', 'b');
foreach ($a as &$g) { }
foreach ($a as $g) { }
echo("<pre>");
var_dump($a);
?>
 
Try to guess the output. Then run the code and see teh real output.

I am still not sure whether it's a bug or a very non-cool feature.

Re: FTW

Posted: Tue Jul 07, 2009 11:06 am
by ubax
it's not a bug, just a trap.

Re: FTW

Posted: Tue Jul 07, 2009 11:10 am
by genconv
It's interesting:)

Re: FTW

Posted: Tue Jul 07, 2009 11:25 am
by Mark Baker
Try the minor variant:

Code: Select all

 
<?php
$a = array('a', 'b');
foreach ($a as &$g) { }
foreach ($a as $h) { }
echo("<pre>");
var_dump($a);
?>
 
and see the difference

or this:

Code: Select all

 
<?php
$a = array('a', 'b', 'c');
foreach ($a as &$g) { }
foreach ($a as $g) { }
echo("<pre>");
var_dump($a);
?>
 
Note that it's always the last element in the array


Then go to the PHP reference page for foreach, and read the warning:
Reference of a $value and the last array element remaion even after the foreach loop. It is recommended to destroy ity by unset

Code: Select all

 
<?php
$a = array('a', 'b');
foreach ($a as &$g) { }
unset ($g);
foreach ($a as $h) { }
echo("<pre>");
var_dump($a);
?>