Php method Instance code for calculating the sum of all values in a multidimensional array

Source: Internet
Author: User
arrays, if you have experienced programming in other languages, you will be familiar with the concept of arrays. Because of the array, you can refer to a series of variables with the same name and identify them with numbers (indexes). In many cases, using arrays can shorten and simplify the program, because you can use index values to design a loop to efficiently handle many situations. The array has upper and lower bounds, and the elements of the array are contiguous within the upper bound.
multidimensional arrays, which sometimes require tracking information in an array of records. For example, to keep track of every pixel on your computer screen, you need to reference its X, Y coordinates. You should store the values in a multidimensional array.

This article mainly introduces the method of PHP to calculate the sum of all the values in multidimensional array, and it involves the technique of PHP recursive invocation for multidimensional arrays.

The PHP built-in function array_sum () function returns the sum of all the values in the array, returning only the sum of one-dimensional arrays;

Calculate all the values of the multidimensional array and the custom function is necessary;

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);

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.