PHP method example code for calculating the sum of all values ​​in a multidimensional array

怪我咯
Release: 2023-03-13 14:36:02
Original
1497 people have browsed it

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);
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!