How to Calculate the Median of an Array of Numbers in PHP?

You can calculate the median of an array of numbers in PHP in the following steps:

  1. Sort the array in ascending order;
  2. Determine the median, which would be one of the following:
    1. Element at the middle index if the array has an odd number of elements, or;
    2. Average of the two elements at the middle indexes if the array has an even number of elements.

For example, you can implement this in the following way:

function median(array $arr): float|int
{
    // 1: sort array in ascending order
    sort($arr);

    $totalArrElems = count($arr);
    $middleIndex = $totalArrElems / 2;

    // 2.1: if odd, return middle element
    if ($totalArrElems % 2 !== 0) {
        return $arr[floor($middleIndex)];
    }

    // 2.2: if even, return average of two middle elements
    return ($arr[$middleIndex - 1] + $arr[$middleIndex]) / 2;
}

For arrays with an odd length, rounding down the middle index (i.e. floor($middleIndex) is needed because dividing an odd array length by 2 would result in a fraction.

For example, using this function you can calculate the median of an array of numbers in the following way:

var_dump(median([1, 2])); // 1.5
var_dump(median([4, 1, 7])); // 4
var_dump(median([3, 7, 5, 1, 8, 9])); // 6
var_dump(median([39, 3, 14, 29, 23, 13, 23, 23, 40, 23, 21, 5, 7, 12, 56])); // 23

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.