Skip to content

Instantly share code, notes, and snippets.

@fdcore
Created January 21, 2018 13:29
Show Gist options
  • Save fdcore/11682a8d4ecdef52ac959d7fd9c15d72 to your computer and use it in GitHub Desktop.
Save fdcore/11682a8d4ecdef52ac959d7fd9c15d72 to your computer and use it in GitHub Desktop.
Высчитываение средней медианы
<?php
/*
Высчитываение средней медианы
@params array массив чисел
*/
function array_median($array) {
// perhaps all non numeric values should filtered out of $array here?
$iCount = count($array);
if ($iCount == 0) {
throw new Exception('Median of an empty array is undefined');
}
// if we're down here it must mean $array
// has at least 1 item in the array.
$middle_index = floor($iCount / 2);
sort($array, SORT_NUMERIC);
$median = $array[$middle_index]; // assume an odd # of items
// Handle the even case by averaging the middle 2 items
if ($iCount % 2 == 0) {
$median = ($median + $array[$middle_index - 1]) / 2;
}
return $median;
}
// пример
echo array_median([12, 16, 80, 70, 11, 14, 13, 20, 10]); // => 14
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment