|
Posted by Edward Vermillion on 09/07/05 20:38
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:
>
>
>> 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
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!
[Back to original message]
|