<?php
print_r(meanMedianAndMode([8, 7, 2, 4, 2]))."\n";
print_r(meanMedianAndMode([8, 7, 2, 4, 2, 7]))."\n";
function meanMedianAndMode($nums) {
$count = count($nums);
sort($nums);
//Calculates Median
if ($count%2 == 0) {
$median = ($nums[$count/2]+$nums[$count/2-1])/2;
} else {
$median = $nums[floor($count/2)];
}
// Calculates Mode
$counted = array_count_values($nums);
$max = max($counted);
// Checks if there is more than one Mode
$counted_max = array_count_values($counted);
if ($counted_max[$max] == 1) {
$mode = array_search($max, $counted);
} else {
foreach ($counted as $key => $value) {
if ($value == $max) {
$mode[] = $key;
}
}
}
return [
'mean' => array_sum($nums) / $count,
// average number
'median' => $median,
'mode' => $mode
];
}