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

Your name:

Reply:


Posted by Jordan Miller on 09/07/05 20:22

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




On Sep 7, 2005, at 12:14 PM, Sabine wrote:



> Hello to all,
>
> is it possible to assign values to the array for which I do the
> foreach-loop?
>
> foreach ($_SESSION['arr1'] as $arr1) {
> foreach ($_SESSION['arr2'] as $arr2) {
> if ($arr1['id'] == $arr2['id']) {
> $arr1['selected'] = true;
> }
> } }
>
> I think $arr1 is only a temp-var, so the assignment won't reflect
> on $_SESSION['arr1'] . Is that right?
> Surely I can do it with a for-loop, but those arrays are a bit
> complex and a foreach would be much easier to read.
>
> Thanks in advance for your answers
> Sabine
>
> --
> PHP General Mailing List (http://www.php.net/)
> To unsubscribe, visit: http://www.php.net/unsub.php
>
>
>
>
>
>

[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

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