Re: Assign values in foreach-loop
| From: | Edward Vermillion | Date: | Wed, 07 Sep 2005 17:38:39 +0000 |
| Subject: | Re: Assign values in foreach-loop | ||
| References: | 1 2 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-221982@lists.php.net to get a copy of this message | ||
Jordan Miller wrote:
Hello, You simply need the $key variable, then you can set a new value for $arr[$key] for each array element: <?php $arr = array(1, 2, 3, 4); foreach ($arr as $key => $value) { $arr[$key] = $value * 2; } // $arr is now array(2, 4, 6, 8) ?> http://www.php.net/foreach If you have PHP 5, you can perhaps more efficiently do this:Or you can do it like that... Totally brain-faded on the $key bit. I've been bitten by this so many times that it's just in my head that you can't permanently modify the array. Cool stuff on the v5 referencing, I guess I'm gonna have to go back through the manual on everything and not just the new stuff. Thanks!As of PHP 5, you can easily modify array's elements by preceding $value with &. This will assign reference instead of copying the value. <?php $arr = array(1, 2, 3, 4); foreach ($arr as &$value) { $value = $value * 2; } // $arr is now array(2, 4, 6, 8) ?>Jordan