How to find the average of an array in php

PHPz
Release: 2023-04-24 09:22:25
Original
875 people have browsed it

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;
}
Copy after login

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

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

Method 3: Using foreach loop

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

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);
Copy after login

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
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!