Re: & confusion, mad bug or unexpected behaviour

From: Date: Thu, 08 Jun 2000 02:38:11 +0000
Subject: Re: & confusion, mad bug or unexpected behaviour
References: 1  Groups: php.dev 
Request: Send a blank email to php-dev+get-20525@lists.php.net to get a copy of this message
> 1) try this, works as expected: > > $pos=array(3=>'a',5=>'b',6=>'c',7=>'d'); > $positions=&$pos; // important line > > foreach($positions AS $pos1 =>$char1) { > list($pos2,$char2)=each($positions); > echo $pos1.$pos2."<BR>"; } > > 2) and this, one line modified, does not work as expected, the foreach() > seems not to move the cursor, change: > > $positions=&$pos; // important line > > > to > > $positions=$pos; > > if it´s a bug, it´s a bad one - tested on php4 release > if not I would expect another behaviour > Actually, no, this is the correct behavior since foreach operates on a copy of the variable, when you assign $pos to $positions like so: $positions = &$pos; You are passing a reference to an array, a foreach loop the copies that reference to an array and operates on that, therefore, your still operating on the $pos array. However in the second example you copy the array onto the $positions variable, and then foreach operates on a copy of that, thus not modifying the $positions array at all. In this case you should just use a while loop to yield the expected behavior. Sterling sterling@designmultimedia.com

« previous php.dev (#20525) next »