Created
December 23, 2009 23:33
-
-
Save ischenkodv/262906 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
function calculate_median($arr) { | |
$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; | |
} | |
function calculate_average($arr) { | |
$count = count($arr); //total numbers in array | |
foreach ($arr as $value) { | |
$total = $total + $value; // total value of array numbers | |
} | |
$average = ($total/$count); // get average value | |
return $average; | |
} |
Rewritten from javascript https://stackoverflow.com/a/45309555/2298745
Median PHP:
function median($values) {
$count = count($values);
if ($count === 0) return null;
asort($values);
$half = floor($count / 2);
if ($count % 2) return $values[$half];
return ($values[$half - 1] + $values[$half]) / 2.0;
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
As BramVanroy and other mentioned, array needs to be sorted. In my case I used
sort($arr);
.