find the variance of all elements in an array in php

To find the variance of all elements in an array in PHP, you can use the array_sum() and pow() functions in combination with the count() function. The following function will calculate the variance of all elements in an array:

main.php
function variance($arr) {
    $count = count($arr);
    $mean = array_sum($arr) / $count;
    $variance = 0.0;
    foreach($arr as $i) {
        $variance += pow($i - $mean, 2);
    }
    return $variance / ($count - 1);
}
223 chars
10 lines

You can use this function like this:

main.php
$array = [1,2,3,4,5];
echo variance($array); // Output: 2.5
60 chars
3 lines

This will output the variance of all elements in the array, which is 2.5.

gistlibby LogSnag