Home > Article > Backend Development > PHP method example code for calculating the sum of all values in a multidimensional array
Array, if you have experience in programming in other languages, you must be familiar with the concept of arrays. Thanks to arrays, you can refer to a series of variables with the same name and identify them numerically (indexed). In many situations, using arrays can shorten and simplify programs because you can design a loop using index values to handle multiple situations efficiently. Arrays have upper and lower bounds, and the elements of the array are continuous within the upper and lower bounds.
Multidimensional array, sometimes it is necessary to track and record relevant information in the array. For example, to track every pixel on a computer screen, you need to reference its X and Y coordinates. At this time, multidimensional arrays should be used to store values.
This article mainly introduces the method of PHP calculating the sum of all values in Multidimensional arrays, involving PHP's recursive calling skills for multidimensional arrays
php Built-in functions array_sum() function returns the sum of all values in the array. It can only return the sum of one-dimensional array;
calculates the sum of all values in a multi-dimensional array. It’s time to custom function;
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);
The above is the detailed content of PHP method example code for calculating the sum of all values in a multidimensional array. For more information, please follow other related articles on the PHP Chinese website!