Re: Simple array problem

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

 



Quoting Brian Dunning <brian@xxxxxxxxxxxxxxxx>:

I'm trying to add a number to a value in an array. Pretend I have this:

$new_value = array('orange', 2);
$arr = array(
	array('blue', 4),
	array('orange', 5),
	array('green', 6));

I want to add the new value to the existing matching array element, so
I end up with this:

$arr = array(
	array('blue', 4),
	array('orange', 7),
	array('green', 6));

Seems like it should be really simple but all the ways I can figure out
to do it are too kludgey.




Just loop through the array to update. And use in_array to check if the key to update exists. Then you can do $array[$key][1] = $newValue.

Something like this maybe:

function updateArray(&$array, $update)
{
    list($updateKey, $updateValue) = $update;
    foreach ($array as $key => $subArray) {
        if (in_array($updateKey, $subArray)) {
            $array[$key][1] = $updateValue;
        }
    }
}

updateArray($arr, $new_value);
var_dump($arr);

--
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