1

I've searched around 1 h. It seems to be duplicate, but I can't find something to help me.

$a = array('aa'=>10, 'bb'=>2, 'cc'=>5);
$b = array('aa'=>1, 'bb'=>20, 'dd'=>11);
$c = array('aa'=>3);
$d = array('ee'=>5);

How can I sum all of this in one array which should look like:

$summed = array('aa'=>14,'bb'=>22,'cc'=>5,'dd'=>11,'ee'=>5);
splash58
  • 26,043
  • 3
  • 22
  • 34
Botea Florin
  • 543
  • 6
  • 24

4 Answers4

2

Merge all arrays and sum values if it's an array

$res = array_merge_recursive($a, $b, $c,$d);
foreach($res as &$x) {
    if (is_array($x)) {
       $x = array_sum($x); 
    }
}
print_r($res);

demo

splash58
  • 26,043
  • 3
  • 22
  • 34
  • ...you _could_ even force the `$x` to an array and omit the conditional like: `$x = array_sum((array)$x);` Either way, `array_merge_recursive()` is the best tool for the job because the arrays are associative. An excellent piece of code. – mickmackusa Jun 24 '18 at 12:47
0

You could try something like this :

$summed=[] ;
foreach ([$a,$b,$c,$d] as $arr) {
    foreach ($arr as $k => $v) {
        if (!isset($summed[$k])) $summed[$k] = 0;
        $summed[$k]+=$v;
    }
}
print_r($summed);

Will outputs :

Array
(
    [aa] => 14
    [bb] => 22
    [cc] => 5
    [dd] => 11
    [ee] => 5
)
Syscall
  • 19,327
  • 10
  • 37
  • 52
0
$a = array('aa'=>10, 'bb'=>2, 'cc'=>5);
$b = array('aa'=>1, 'bb'=>20, 'dd'=>11);
$c = array('aa'=>3);
$d = array('ee'=>5);

$arrays = [$a, $b, $c, $d];

$result = [];

foreach ($arrays as $value_array) {
    foreach ($value_array as $key => $value) {
        if (array_key_exists($key, $result)) {
            $result[$key] += $value;
        } else {
            $result[$key] = $value;
        }
    }
}
Friedrich Roell
  • 437
  • 1
  • 5
  • 14
0

A method that uses less looping than iterating the full arrays is to get all keys from the arrays and use array_column and array_sum.

$a = array('aa'=>10, 'bb'=>2, 'cc'=>5);
$b = array('aa'=>1, 'bb'=>20, 'dd'=>11);
$c = array('aa'=>3);
$d = array('ee'=>5);

$arr = [$a,$b,$c,$d];

$keys = array_keys(array_merge($a,$b,$c,$d)); //merge arrays and get keys ['aa','bb'] etc.
Foreach($keys as $key){
    // Sum column of 'aa', 'bb' etc from array
    $sums[$key] = array_sum(array_column($arr, $key));
}

Var_dump($sums);

https://3v4l.org/ZHtWf

Andreas
  • 23,610
  • 6
  • 30
  • 62