user2124412
user2124412

Reputation: 13

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.

Upvotes: 1

Views: 641

Answers (2)

mickmackusa
mickmackusa

Reputation: 47874

Isolate the column, sum the values. Demo

echo array_sum(array_column($array, 4));

Upvotes: 0

John Conde
John Conde

Reputation: 219804

<?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

Upvotes: 1

Related Questions