FartMachine4U
FartMachine4U

Reputation: 115

PHP - sum of two simple arrays to create

Array1 ( [a] => 1 [b] => 2 [c] => 7 [d] => ) 

Array2 ( [a] => 2 [x] => 4 [y] =>  )

I tried these to add the two arrays to get a new array where matching keys values are added. The final array would be:

Array3 ( [a] => 3 [b] => 2 [c] => 7 [d] => [x] => 4 [y] => ) 

I am looking at, but can't get the final array to display all keys:

    foreach($array1 as $key => $val)
        {
        $final_value = $val + $array2[$key]; 
        $final_array[] = array($key=>$final_value);
        }

Is that I have, but does not work.

I also looked at Jonah's suggestion at: Merge 2 Arrays and Sum the Values (Numeric Keys)

Upvotes: -1

Views: 73

Answers (3)

miltos
miltos

Reputation: 1019

try this code

$Array3 = $Array1;
foreach ($Array2 as $k => $v) {
    $Array3[$k] = $Array3[$k] + $Array2[$k];
}

Upvotes: 0

Paul Facklam
Paul Facklam

Reputation: 1633

Here we go:

$firstArray = array ('a' => 1, 'b' => 2, 'c' => 7, 'd' => 0); // d must have a value
$secondArray = array ('a' => 2, 'x' => 4, 'y' =>  0); // y must have a value

$keys = array();
$result = array();

foreach($firstArray as $key => $value) {
    $keys[] = $key;
}

foreach($secondArray as $key => $value) {
    if(! in_array($key, $keys)) {
         $keys[] = $key;
    }
}

foreach($keys as $key) {

    $a = 0;
    $b = 0;

    if(array_key_exists($key, $firstArray)) {
        $a = $firstArray[$key];
    }

    if(array_key_exists($key, $secondArray)) {
        $b = $secondArray[$key];
    }

    $result[$key] = $a + $b;
}

print_r($result);

Output:

Array ( [a] => 3 [b] => 2 [c] => 7 [d] => 0 [x] => 4 [y] => 0 )

Upvotes: 2

Emz
Emz

Reputation: 1280

This goes through both arrays and compares their key to each other. It can be optimized a bit by checking so that it doesn't compare itself against previous values.

$array1 = array (
    'a' => 1,
    'b' => 2,
    'c' => 7,
    'd' => // needs a value
);

$array2 = array (
    'a' => 2
    'b' => 4
    'c' => // needs a value
);

foreach ($array1 as $key1 => $value1) {
    foreach ($array2 as $key2 => $value2) {
        if ($key1 == $key2) {
            $array3[$key1] = $value1 + $value2;
        }
    }   
}

Upvotes: 0

Related Questions