PHP Array_Sum on multi dimensional array

I don’t think there’s any built-in function that would let you sum the values of a multidimensional array. However, here’s a way of doing it using a lambda-style function.

Let’s suppose this is your array:

 [items] => Array
        (
            [0] => Array
                (
                    [ID] => 11
                    [barcode] => 234334
                    [manufacturer] => Dell
                    [model] => D630
                    [serial] => 324233
                    [current_value] => 1100.00
                )

            [1] => Array
                (
                    [ID] => 22
                    [barcode] => 323552
                    [manufacturer] => Dell
                    [model] => D630
                    [serial] => 234322
                    [current_value] => 1500.00
                )

        )

You could create a function that you could pass values to:

$array_value_sum = create_function('$array,$key', '$total = 0; foreach($array as $row) $total = $total + $row[$key]; return $total;');

And then use it like so:

echo "Total Current Value" . $array_value_sum($obj['items'], 'current_value');

Leave a Comment