Re: re-keying an array

From: Date: Wed, 05 May 2004 03:17:33 +0000
Subject: Re: re-keying an array
References: 1 2 3 4 5 6 7 8  Groups: php.general 
Request: Send a blank email to php-general+get-185387@lists.php.net to get a copy of this message
Justin Patrin wrote:
Richard Harb wrote:
Uh, I was wrong... Foreach evaluates only once at initialisation... You can even unset the array once into the loop and it still works perfectly well (not that I recommend this as good practice or whatever, just did some checking to be sure :) Richard
That will work because foreach iterates over a copy of the array. I often do things like: foreach($arr as $key => $val) { if(some condition) {
    unset($arr[$key]);
} }
Just one other thought. For those of you using PHP5, you can change the actual values in an array by using a reference. foreach ($arr as $key => &$val) { if ($condition) {
    $val = $newval;
} } Putting the & in front of the $val tells PHP to use references, which would change the values of the original array. Just another way to skin a cat :)

« previous php.general (#185387) next »