Reply to Re: [PHP] Assign values in foreach-loop

Your name:

Reply:


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]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация