Indhiyan V
Indhiyan V

Reputation: 31

How to add the key and values in array?

for example

$array1 = array(item1=>5,item2=>7);
$array2 = array(item1=>5,item3=>7);

Actually i want to first check the array, if same key exist means value should be (arithmetically) added otherwise if not exists then it directly pushed to the array.

my output will be like

$nov-2014 =array(item1=>10,item2=>7,item3=>7)

Upvotes: 2

Views: 102

Answers (4)

pavel
pavel

Reputation: 27092

I think there is no built PHP function, use foreach.

$array1 = array('item1' => 5, 'item2' => 7);
$array2 = array('item1' => 5, 'item3' => 7);
$result = $array1;

foreach ($array2 as $key => $val) {
    if (isset($result[$key])) {
        $result[$key] += $val;
    } else {
        $result[$key] = $val;
    }
}

/*
    Output:
    Array
    (
        [item1] => 10
        [item2] => 7
        [item3] => 7
    )
*/

Upvotes: 2

Serge
Serge

Reputation: 417

Try this:

$array1 = array(
    'item1' => 5,
    'item2' => 7
);
$array2 = array(
    'item1' => 5,
    'item3' => 7
);
$array_new = $array2;
foreach ($array1 as $key => $value) {
    if (!in_array($key, $array2)) {
        $array_new[$key] = $value + $array2[$key];
    }
}

Upvotes: 3

Kevin
Kevin

Reputation: 41885

You can just plainly use a simple for and a foreach for that purpose. Of course create the final container. Initialize values, then just continually add thru keys:

$array1 = array('item1'=>5,'item2'=>7);
$array2 = array('item1'=>5,'item3'=>7);

$result = array();
for($x = 1; $x <= 2; $x++) {
    foreach(${"array$x"} as $key => $values) {
        if(!isset($result[$key])) $result[$key] = 0; // initialize
        $result[$key] += $values; // add
    }
}

print_r($result);

Sample Output

Upvotes: 3

qrazi
qrazi

Reputation: 1391

Try array_merge. For associative arrays, this will keep same keys

Upvotes: -2

Related Questions