find the median of a list of numbers in php

To find the median of a list of numbers in PHP, you can follow these steps:

  1. First, sort the array in ascending order using sort() function in PHP.
  2. Get the length of the array using count() function.
  3. Check if the length of the array is even or odd.
  4. If the length of the array is odd, the median will be the middle number of the sorted array, which can be accessed using the index count($array)/2.
  5. If the length of the array is even, the median will be the average of the two middle numbers of the sorted array, which can be calculated by accessing the two middle numbers with indexes (count($array)/2)-1 and count($array)/2 and then dividing their sum by 2.

Here's the code snippet:

main.php
function getMedian($array) {
    sort($array);
    $count = count($array);
    $middle = floor($count/2);
    if($count % 2 == 0) {
        $median = ($array[$middle-1] + $array[$middle]) / 2;
    } else {
        $median = $array[$middle];
    }
    return $median;
}

// Example usage
$array = [2, 5, 1, 7, 3, 9, 8, 4, 6];
echo getMedian($array); // Output: 5
362 chars
16 lines

related categories

gistlibby LogSnag