30 seconds of PHP

  Back to Home

median

matharraybeginner

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];
}