Re: Simple array problem

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



I think the problem is easier... and also the solutions doing a "for"
instead of "foreach" are not good solutions because if the array is not
index-consecutive the loop fails.

So, if you has an array with the colors as indexes and the integer value X
as the value for that position of the array, updating is very easy.

You have an array such as:

$array = array( );

$array['blue'] = 4;

$array['orange'] = 5;

$array['green'] = 6;

....

So if you want to update the key 'orange' with a new value $new_value is as
easy as:

$array['orange'] += $new_value;

As the new value is being passed as an array so as to update it, it should
be like:

$new_value = array('orange',2);

So you have to do a foreach in the $new_value array like:

foreach ($new_value as $key => $value){

   if(in_array($key,$array)){

      $array[$key] += $value;

   }

}

I think that solution works and is the easiest way to do it.

Cheers,

Roberto

On 01/07/2008, tedd <tedd.sperling@xxxxxxxxx> wrote:
>
> At 9:35 AM +0100 7/1/08, Richard Heyes wrote:
>
>> Brian Dunning wrote:
>>
>>> Seems like it should be really simple but all the ways I can figure out
>>> to do it are too kludgey.
>>>
>>
>> It's rather easy:
>>
>> for ($i=0; $i<count($arr); $i++) {
>>    if ($arr[$i][0] == $new_array[0]) {
>>        $arr[$i][1] += $new_array[1];
>>        break; // Optional - means the first "orange" found will be
>>               // updated only
>>    }
>> }
>>
>> --
>> Richard Heyes
>>
>
> Small correction:
>
> for ($i=0; $i<count($arr); $i++)
>   {
>    if ($arr[$i][0] == $new_value [0])
>      {
>        $arr[$i][1] += $new_value [1];
>        break; // Optional - means the first "orange" found will be
>               // updated only
>       }
>   }
>
> See here:
>
> http://www.webbytedd.com/b1/array/
>
> But, I'm not sure as to why you (Brian) would want to do that anyway.
>
> tedd
> --
> -------
> http://sperling.com  http://ancientstones.com  http://earthstones.com
>
> --
> PHP General Mailing List (http://www.php.net/)
> To unsubscribe, visit: http://www.php.net/unsub.php
>
>

[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux