Example of how PHP calculates the average value of an exclusive multi-dimensional array-PHP source code

Source: Internet
Author: User
PHP's method for calculating the average value of an exclusive multi-dimensional array is just to traverse the array. Is there any other way to achieve this? Let's take a look at it. PHP's method for calculating the average value of an exclusive multi-dimensional array is just to traverse the array. Is there any other way to achieve this? Let's take a look at it.

Script ec (2); script

In php, a common method for finding a multidimensional, exclusive multi-dimensional array is recursion, as shown in the following code:

$ Count = 0; $ sum = 0;
Function avgarr ($ arr)
{
Global $ sum, $ count; // global variable
Foreach ($ arr as $ value) {// cyclically traverse the Array
If (is_array ($ value )){
Avgarr ($ value); // Recursion
}
Elseif (is_int ($ value )){
$ Sum + = $ value;
$ Count ++;
}
}
Return $ sum/$ count; // returns the average value.
}

At the beginning, I wrote the above Code and tested an array. The result is OK. I believe that success has been achieved. But what should I do? Can I continue to use this function after finding the average value of an array? No, because the defined global variables have changed and cannot be reset automatically. After an array is obtained using this function, it is useless and cannot be used any more. Unless $ sum and $ count are reset to zero each time. Isn't it too troublesome? In this way, check the Code:

Function avgarr2 ($ arr ){
$ Count = 0; $ sum = 0;
Echo avgarr ($ arr );
}

Place the above function in another function, and use this function to reset $ sum and $ count each time. In this way, the function is universal.

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.