Search code examples
phparraysmultidimensional-arraysum

Sum each column of a 2d array


I need a little help with summing up the columns in a two-dimensional array.

Eg Multidimensional array

Array
(
    [0] => Array
        (
            [0] => 30
            [1] => 5
            [2] => 6
            [3] => 7
            [4] => 8
            [5] => 9
            [6] => 2
            [7] => 5
        )

    [1] => Array
        (
            [0] => 50
            [1] => 4
            [2] => 8
            [3] => 4
            [4] => 4
            [5] => 6
            [6] => 9
            [7] => 2
        )
)

I want to have a result array that will hold the columnar sums of both rows.

Array
(
    [0] => 80
    [1] => 9
    [2] => 14
    [3] => 11
    [4] => 12
    [5] => 15
    [6] => 11
    [7] => 7
)

Solution

  • This should work for arrays like the one of your example ($arr is an array like the one in your example, I haven't defined it here for simplicity's sake):

    $res = array();
    foreach($arr as $value) {
        foreach($value as $key => $number) {
            (!isset($res[$key])) ?
                $res[$key] = $number :
                $res[$key] += $number;
        }
    }
    
    print_r($res);