Re: foreach nastiness with references (bug #21702)

From: Date: Wed, 22 Jan 2003 06:03:40 +0000
Subject: Re: foreach nastiness with references (bug #21702)
References: 1 2  Groups: php.dev 
Request: Send a blank email to php-dev+get-93592@lists.php.net to get a copy of this message
John Coggeshall wrote:
To answer part of your question: What the documentation means is that <?php foreach($foo as $key=>$val) { $val = "newval"; } ?> Will not change every element in the $foo array to "newval". However, although $foo cannot be modified by modifying $key and $val the internal array pointer WILL increment as if you were actually working on that array directly.. So in order to restore the internal array pointer back to the start of the array you'd need a call to reset($foo) first.
If that's what the documentation means, then the documentation is wrong. Just try it. What you say is true ONLY when there's a reference to the array, but that isn't mentioned in the docs. Cut'n'paste: <?php $a = array(1,2,3); #$r =& $a; echo "current before foreach: " . current($a) . "<br>\n"; foreach($a as $b) {
    echo "- value in cycle: " . $b . "<br>\n";
    echo "-- current in cycle: " . current($a) . "<br>\n";
} echo "current before foreach: " . current($a) . "<br>\n"; ?> Try it, and the delete the hash mark and try again. Regards, Vaclav Dvorak

« previous php.dev (#93592) next »