Forked from ischenkodv/Calculate median and average in PHP
Last active
May 13, 2016 15:50
-
-
Save bspavel/be5047d64fb4ca409b48673bd83aa75c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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