FTW

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
ubax
Forum Newbie
Posts: 11
Joined: Wed Jun 10, 2009 10:45 am

FTW

Post 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.
ubax
Forum Newbie
Posts: 11
Joined: Wed Jun 10, 2009 10:45 am

Re: FTW

Post by ubax »

it's not a bug, just a trap.
User avatar
genconv
Forum Commoner
Posts: 34
Joined: Sun Jul 05, 2009 9:27 am

Re: FTW

Post by genconv »

It's interesting:)
Mark Baker
Forum Regular
Posts: 710
Joined: Thu Oct 30, 2008 6:24 pm

Re: FTW

Post 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);
?>
 
Post Reply