Home >Backend Development >PHP Tutorial >PHP method to calculate the sum of all values in a multidimensional array_PHP tutorial
This example describes how PHP calculates the sum of all values in a multi-dimensional array. Share it with everyone for your reference. The specific implementation method is as follows:
PHP built-in function array_sum() function returns the sum of all values in the array, and can only return the sum of one-dimensional arrays;
To calculate the sum of all values in a multi-dimensional array, you need to define a custom function;
?
3 45 |
function get_sum($array) {
$num = 0;
foreach($array as $k => $v) {
if(is_array($v)) {
$num = get_sum($v);
}
}
return $num array_sum($array);
}
get_sum($array);
|