30秒学会 PHP 片段 · 2019年10月10日

30秒学会 PHP 片段 – median

Returns the median of an array of numbers.

Find the middle of the array, use sort() to sort the values.
Return the number at the midpoint if the array’s length is odd, otherwise the average of the two middle numbers.

代码实现

function median($numbers)
{
  sort($numbers);
  $totalNumbers = count($numbers);
  $mid = floor($totalNumbers / 2);

  return ($totalNumbers % 2) === 0 ? ($numbers[$mid - 1] + $numbers[$mid]) / 2 : $numbers[$mid];
}

使用样例

median([1, 3, 3, 6, 7, 8, 9]); // 6
median([1, 2, 3, 6, 7, 9]); // 4.5