Home  >  Article  >  Backend Development  >  How to find the average of a two-dimensional array in php

How to find the average of a two-dimensional array in php

PHPz
PHPzOriginal
2023-04-26 14:28:31920browse

In PHP, requiring the average of a two-dimensional array can be achieved by the following method:

First, we need to traverse the entire two-dimensional array in order to add the value of each element. This can be achieved by using a double loop. The first loop iterates over the outer array of the array, while the second loop iterates over the inner array.

Next, we add the values ​​of all elements and count the number of elements. Then, the average of the array is obtained by dividing the sum of the elements by the number of elements.

Finally, we return the calculated average to the caller.

The specific implementation code is as follows:

function getAverage($arr) {
    $sum = 0;
    $count = 0;

    foreach ($arr as $subArr) {
        foreach ($subArr as $value) {
            $sum += $value;
            $count++;
        }
    }

    $average = $sum / $count;

    return $average;
}

In the above example, we use two foreach loops, one for traversing the external array and the other for traversing the internal array. We use the variable $sum to save the sum of all elements, and the variable $count to count the number of elements. Finally, we divide $sum by $count to get the average of the array and return the result to the caller.

You can copy the above code into a text editor, store it as a .php file, and then call this function when you need to calculate the average of a two-dimensional array. For example:

$arr = array(
    array(1, 2, 3),
    array(4, 5, 6),
    array(7, 8, 9)
);

$average = getAverage($arr);
echo "The average is: $average";

The above code will generate the following output: The average is: 5.

In the above example, we used a two-dimensional array consisting of three sub-arrays with an average value of 5.

The above is the detailed content of How to find the average of a two-dimensional array in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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