I am trying to calculate Z-scores using PHP. Essentially, I am looking for the most efficient way to calculate the mean and standard deviation of a data set (PHP array). Any
This is the same std dev code from the php pages mentioned in the top answer, but modernized a bit, without the one-line array magic and separate helper function:
/**
* Calculates the standard deviation of an array of numbers.
* @param array $array The array of numbers to calculate the standard deviation of.
* @return float The standard deviation of the numbers in the given array.
*/
function calculateStdDev(array $array): float
{
$size = count($array);
$mean = array_sum($array) / $size;
$squares = array_map(function ($x) use ($mean) {
return pow($x - $mean, 2);
}, $array);
return sqrt(array_sum($squares) / ($size - 1));
}