Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save bspavel/be5047d64fb4ca409b48673bd83aa75c to your computer and use it in GitHub Desktop.
Save bspavel/be5047d64fb4ca409b48673bd83aa75c to your computer and use it in GitHub Desktop.
<?php
//https://en.wikipedia.org/wiki/Median
function calcAvg($arr)
{
$avg = (array_sum($arr)/count($arr));
return $avg;
}
function calcMedian($arr)
{
asort($arr);
$newArr=[];
foreach($arr as $val){
$newArr[]=$val;
}
$arr=$newArr;unset($newArr);
$count = count($arr); //total numbers in array
$middleval = floor(($count-1)/2); // find the middle value, or the lowest middle value
if($count % 2) { // odd number, middle is the median
$median = $arr[$middleval];
} else { // even number, calculate avg of 2 medians
$low = $arr[$middleval];
$high = $arr[$middleval+1];
$median = (($low+$high)/2);
}
return $median;
}
$arr=[11, 9, 3, 5, 5];
echo 'Median:'.calcMedian($arr),
'<br />Avg:'.calcAvg($arr);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment