Horje
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



Reffered: https://www.geeksforgeeks.org


PHP

Related
Binary to Octal Converter in PHP Binary to Octal Converter in PHP
How to Filter a Collection in Laravel? How to Filter a Collection in Laravel?
PHP Program to Convert a Given Number to Words PHP Program to Convert a Given Number to Words
PHP iconv_strlen() Function PHP iconv_strlen() Function
PHP Determinant of a Matrix PHP Determinant of a Matrix

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
15