PHP program to find standard deviation of values within an array


To find standard deviation of values within an array, the code is as follows in PHP −

Example

 Live Demo

<?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));
?>

Output

The standard deviation of elements in the array is 35.423156268181

A function named ‘std_deviation’ is defined counts the number of elements in the array and initializes the variance to 0. The average is calculated as the sum of elements in the array divided by the total number of elements in the array. Now, a ‘foreach’ loop is run over the array and the variance is calculated by subtracted the average value from every element of the array and squaring it.

When the foreach loop goes to the end, the final variance value is returned as output. Outside that function, an array is defined and that function is called on this array. Relevant output is displayed on the console.

Updated on: 01-Jul-2020

604 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements