Example of PHP seeking the average of an alien multidimensional array

Source: Internet
Author: User

In PHP, the common way to find multi-dimensional arrays is recursively, as in the following code

$count =0; $sum = 0;
function Avgarr ($arr)
{
Global $sum, $count; Global variables
foreach ($arr as $value) {//Loop traversal array
if (Is_array ($value)) {
Avgarr ($value); Recursion
}
ElseIf (Is_int ($value)) {
$sum + + $value;
$count + +;
}
}
return $sum/$count; return average
}

Start by writing the above code, test an array, and the result is OK. Secretly pleased, thought is done. But how about a closer look? Can you continue to use this function after you have evaluated the average of an array? No, because the defined global variable has changed and cannot be reset automatically, after an array is finished with this function, it is discarded and cannot continue to be used. Unless you manually give $sum, $count zeroing. Wouldn't that be too much trouble? There is also this way to look at the code:

function Avgarr2 ($arr) {
$count =0; $sum = 0;
echo Avgarr ($arr);
}

Put the above function in another function, and use this function to reset $sum and $count each time. As a result, 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.