Search code examples
phparraysmultidimensional-arraysum

Sum the values of a column in a 2d array


I need to sum up some values from subarrays in an array.

I have this array

Array
(
    [smecid_2] => Array
        (
            [0] => 1
            [1] => SMEC 55.6
            [2] => 960
            [3] => 864
            [4] => 960
            [5] => 864
        )

    [smecid_6] => Array
        (
            [0] => 3
            [1] => SMEC 55.6 ATEX EX
            [2] => 1290
            [3] => 1161
            [4] => 3870
            [5] => 3483
        )

)

What I want to do is sum up all fields from key [4] of each subarray and be able to echo the total in $total;

In this example $total; would be 4830 (960+3870).

Also, the array could hold more subarrays then these 2, when a user submits more products to order.


Solution

  • <?php
    $array = array
    (
        'smecid_2' => array
            (
                0 => 1,
                1 => 'SMEC 55.6',
                2 => 960,
                3 => 864,
                4 => 960,
                5 => 864,
            ),
    
        'smecid_6' => array
            (
                0 => 3,
                1 => 'SMEC 55.6 ATEX EX',
                2 => 1290,
                3 => 1161,
                4 => 3870,
                5 => 3483,
            )
    
    );
    
    $sum = 0;
    foreach ($array as $subarray)
    {
        $sum += $subarray[4];
    }
    echo $sum;
    

    See it in action