find the median of all elements in an array in php

To find the median of all elements in an array in PHP, you can follow these steps:

  1. Sort the array in ascending order using the sort() function.
  2. Find the middle index of the array using the count() function.
  3. Check if the length of the array is even or odd.
  4. If the length is odd, return the value at the middle index of the sorted array.
  5. If the length is even, calculate the average of the two values at the middle indices of the sorted array and return the result.

Here's the code:

main.php
function findMedian($arr) {
    sort($arr);
    $count = count($arr);
    $mid = floor(($count-1)/2);

    if ($count % 2 == 0) {
        $median = ($arr[$mid] + $arr[$mid+1])/2;
    } else {
        $median = $arr[$mid];
    }

    return $median;
}

// example usage
$array = [3, 1, 4, 2, 5];
$median = findMedian($array);
echo "The median of the array is: " . $median;
372 chars
19 lines

related categories

gistlibby LogSnag