PHP program to find standard deviation of values within an array

Standard deviation measures how spread out values are from the average in a dataset. In PHP, you can calculate it by finding the mean, computing variances, and taking the square root of the average variance.

Syntax

The formula for standard deviation is ?

Standard Deviation = sqrt(sum((value - mean)²) / count)

Example

Here's how to create a function to calculate standard deviation ?

<?php
function std_deviation($my_arr)
{
    $no_element = count($my_arr);
    $var = 0.0;
    $avg = array_sum($my_arr)/$no_element;
    foreach($my_arr as $i)
    {
        $var += pow(($i - $avg), 2);
    }
    return (float)sqrt($var/$no_element);
}
$my_arr = array(67, 89, 93, 102, 4);
echo "The standard deviation of elements in the array is ";
print_r(std_deviation($my_arr));
?>
The standard deviation of elements in the array is 35.423156268181

How It Works

The std_deviation() function works in the following steps ?

  • Count elements: Uses count() to get array size
  • Calculate mean: Divides array_sum() by element count
  • Find variance: For each element, subtracts mean and squares the result using pow()
  • Return result: Takes square root of average variance using sqrt()

Using Built-in Functions

You can also use PHP's statistical functions for a more concise approach ?

<?php
function calculate_std_dev($arr) {
    $mean = array_sum($arr) / count($arr);
    $variance = array_sum(array_map(function($x) use ($mean) {
        return pow($x - $mean, 2);
    }, $arr)) / count($arr);
    return sqrt($variance);
}

$numbers = [67, 89, 93, 102, 4];
echo "Standard deviation: " . round(calculate_std_dev($numbers), 2);
?>
Standard deviation: 35.42

Conclusion

Standard deviation in PHP is calculated by finding the mean, computing squared differences, and taking the square root of their average. Use array_sum(), pow(), and sqrt() functions for efficient calculation.

Updated on: 2026-03-15T09:01:46+05:30

982 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements