How to find the median of an array
Short answer
Sort the array and take the middle element; with an even count, the mean of the two middle ones:
<?php
function median(array $numbers): float
{
sort($numbers);
$count = count($numbers);
$middle = intdiv($count, 2);
return $count % 2 === 1
? $numbers[$middle]
: ($numbers[$middle - 1] + $numbers[$middle]) / 2;
}
echo median([7, 1, 3]), ' ', median([7, 1, 3, 5]);Output:
3 4Why the median beats the mean
One very large value shifts the mean a lot and barely changes the median:
<?php
$salaries = [40, 45, 50, 55, 1000];
sort($salaries);
echo array_sum($salaries) / count($salaries), ' ', $salaries[intdiv(count($salaries), 2)];Output:
238 50