Skip to content

Instantly share code, notes, and snippets.

@psynewave
Created October 26, 2012 18:25
Show Gist options
  • Save psynewave/3960513 to your computer and use it in GitHub Desktop.
Save psynewave/3960513 to your computer and use it in GitHub Desktop.
PHP Median Function
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