Created
October 26, 2012 18:25
-
-
Save psynewave/3960513 to your computer and use it in GitHub Desktop.
PHP Median Function
This file contains hidden or 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 median($numbers){ | |
//loop through each value in the array and if it is a number add it to a new array | |
foreach ($numbers as $num) { | |
if(is_numeric($num)){ | |
$num_array[]=$num; | |
} | |
} | |
rsort($num_array); //sort the array for our operation | |
$count = count($num_array); | |
$mid = $count / 2; | |
return ($count % 2 != 0) ? "$count numbers - median value: " . $num_array[$mid] : "$count numbers - median value: " . ($num_array[$mid-1] + $num_array[$mid])/2; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment