Home >Backend Development >PHP Problem >How to find the average of an array in php

How to find the average of an array in php

PHPz
PHPzOriginal
2023-04-24 09:07:281004browse

In PHP programming, finding the average in an array is a very basic operation. The following are some methods to achieve the average:

Method 1: Use a for loop

function avg($arr){
    $sum = 0;
    $count = count($arr);
    for ($i = 0; $i < $count; $i++){
        $sum += $arr[$i];
    }
    return $sum / $count;
}

Method 2: Use array_sum() and count() functions

function avg($arr){
    return array_sum($arr) / count($arr);
}

Method 3: Using foreach loop

function avg($arr){
    $sum = 0;
    foreach ($arr as $value){
        $sum += $value;
    }
    return $sum / count($arr);
}

Using the above three methods, we can easily implement the average calculation of an array. Suppose we have the following array:

$arr = array(1, 2, 3, 4, 5);

We can call the avg() function and use any of the above three methods to calculate the average of the array:

echo avg($arr);   // 3

Note: The above The code is applicable to all versions of PHP, and the implementation of method 2 may be more concise. At the same time, we can also use the array_reduce() function and functions in other function libraries to implement the averaging function.

The above is the detailed content of How to find the average of an 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