PHP Program To Find Mean and Median of an Unsorted Array

Given an unsorted array, the task is to find the mean (average) and median of the array in PHP. we will see the approach and code example to solve this problem.

Approach

To find the mean of an array, we need to sum up all the elements in the array and then divide the sum by the total number of elements in the array. To find the median of an array, we first need to sort the array in ascending order. If the array has an odd number of elements, the median is the middle element. If the array has an even number of elements, the median is the average of the two middle elements.

Example: This example shows the implementation of the above-explained approach.

PHP
<?php

function findMean($arr) {
    $sum = array_sum($arr);
    $count = count($arr);
    return $sum / $count;
}

function findMedian($arr) {
    sort($arr);
    $count = count($arr);
    $middle = floor($count / 2);
    if ($count % 2 == 0) {
        $median = ($arr[$middle - 1] 
                   + $arr[$middle]) / 2;
    } else {
        $median = $arr[$middle];
    }
    return $median;
}

// Driver Code
$arr = [10, 15, 5, 15, 7, 18];

$mean = findMean($arr);
echo "Mean of Unsorted Array: " . $mean;

$mean = findMedian($arr);
echo "\nMedian of Unsorted Array: " . $mean;

?>

Output
Mean of Unsorted Array: 11.666666666667
Median of Unsorted Array: 12.5