find the standard deviation of all elements in an array in php

To find the standard deviation of all elements in an array in PHP, we can use the following steps:

  1. Calculate the mean of the array.
  2. Calculate the variance of the array.
  3. Calculate the standard deviation using the variance.

Here's the code to accomplish this:

main.php
<?php
function calculateSD($arr)
{
    $n = count($arr);
    $mean = array_sum($arr) / $n;
    $variance = 0.0;

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

    $sd = sqrt($variance / $n);

    return $sd;
}

$arr = array(2, 4, 5, 7, 9);
echo calculateSD($arr);
?>
298 chars
20 lines

In the code above, we first calculate the mean of the array and then iterate through each element to calculate the variance. Finally, we calculate the standard deviation using the variance and return the result.

When we run this code, it will output the standard deviation of the array which is approximately 2.449.

gistlibby LogSnag