How to calculate mean In PHP?

In my earlier articles, we have see calculating arithmetic mean in SQL ServerC#.NET and Python. Now we will see how to calculate mean in PHP. Mean is just the average of the given set of numbers calculated by dividing the sum of all the numbers in the set by the count of numbers in the set. So, we can use PHP’s array_sum() function to get the sum of the numbers in the array. Then, use the count() function to get the count of elements in the array. Finally, divide the sum of the array by the count to get the average, that is the mean of the array. Below is the sample:

Sample code to calculate mean in PHP

<?php
    function getMean($arrInput){ 
        if(is_array($arrInput)){ 

            // Arithmetic Mean = Average of all the numbers in a set
            $mean = array_sum($arrInput)  / count($arrInput);  

            return $mean; 
        }     
    } 

$array = array(220, 100, 190, 180, 250, 190, 240, 180, 140, 180, 190); 

echo 'Mean: '.getMean($array).' <br/>'; 
?>

Output

Mean: 187.27272727273 
Calculate mean In PHP

Related Articles

Reference


Leave your thoughts...

This site uses Akismet to reduce spam. Learn how your comment data is processed.