find the variance of a list of numbers in php

To find the variance of a list of numbers in PHP, you can use the stats_variance function provided in the PHP statistics extension which is built-in from PHP 7.2.0 onwards. If you're using an older version of PHP that doesn't have this extension, you can manually write a function to calculate the variance using mathematical formulas.

Here's an example of how to use stats_variance function in PHP:

main.php
// Define an array of numbers
$numbers = [5, 6, 7, 8, 9];

// Calculate the variance using stats_variance
$variance = stats_variance($numbers);

// Output the result
echo "Variance of the numbers is: " . $variance;
215 chars
9 lines

This will output:

main.php
Variance of the numbers is: 2.5
32 chars
2 lines

If you need to manually calculate the variance for some reason, you can use the following formula:

main.php
Variance = sum((x - mean)^2) / n
33 chars
2 lines

Here's a PHP function that implements this formula:

main.php
function calculate_variance($numbers) {
    $n = count($numbers);
    $mean = array_sum($numbers) / $n;
    $variance = 0.0;

    foreach ($numbers as $number) {
        $variance += pow($number - $mean, 2);
    }

    return $variance / $n;
}

// Define an array of numbers
$numbers = [5, 6, 7, 8, 9];

// Calculate the variance using the custom function
$variance = calculate_variance($numbers);

// Output the result
echo "Variance of the numbers is: " . $variance;
469 chars
21 lines

This will output:

main.php
Variance of the numbers is: 2.5
32 chars
2 lines

gistlibby LogSnag