PHP: Sum values in a multidimensional array
August 2, 2022 ‐ 1 min read
To sum up all the values in a multidimensional array that live under a specific key we make use of two array functions.
First, we call the function array_column()
, which returns to us an array of all the values found for a specific key.
Second, we use the method array_sum()
to sum up all those values.
<?php
$products = [
[
'name' => 'Pen',
'price' => 3,
],
[
'name' => 'Paper',
'price' => 5,
],
];
$sum = array_sum(array_column($products, 'price'));
//=> 8