Masud Rana Masud Rana - 1 month ago 5
PHP Question

I want to add one array key and value with another array values

I want to add one array key and value with another array's value.

If I have arrays as follow:

Array ( [6] => 12 [8] => 9 [10] => 11 )

Array ( [6] => 70 [8] => 10 [9] => 35 [10] => 25 [11] => 25 [12] => 2 )


For example (6 => 12 when processed result in 70 + 2 )

This is the expected output with the two arrays above:

array ([0] => 72 [1] => 45 [2] => 50 )


Thanks In Advance

Answer

Use the following simple solution:

$arr1 = [6 => 12, 8 => 9 , 10 => 11];
$arr2 = [6 => 70, 8 => 10, 9 => 35, 10 => 25, 11 => 25, 12 => 2];

$result = [];
foreach ($arr1 as $k => $v) {
    if (isset($arr2[$k]) && isset($arr2[$v])) {
        $result[] = $arr2[$k] + $arr2[$v];
    }
}

print_r($result);

The output:

Array
(
    [0] => 72
    [1] => 45
    [2] => 50
)