Sometimes, we want to sum all column values in a multi-dimensional array with PHP.
In this article, we’ll look at how to sum all column values in a multi-dimensional array with PHP.
How to sum all column values in a multi-dimensional array with PHP?
To sum all column values in a multi-dimensional array with PHP, we can use the array_column
function to get all the column values.
Then we use array_sum
to sum up the values.
For instance, we write
$sum = array_sum(array_column($input, 'val'));
to call array_column
to get the values in the $input
array with key 'val'
.
Then we call array_sum
to sum up all the values returned by array_column
.
Conclusion
To sum all column values in a multi-dimensional array with PHP, we can use the array_column
function to get all the column values.
Then we use array_sum
to sum up the values.