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

1
  • It is unclear and unexpected to have blank values in your input arrays. This missing component affects how answers are constructed and makes this page difficult to answer confidently. Commented Jan 14, 2024 at 12:21

3 Answers 3

2

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 )

Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

The 'if ($key1 == $key2)' will be true only if elements in same position have the same key name, otherwise it will not do the total.
0

try this code

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.