-
-
Notifications
You must be signed in to change notification settings - Fork 586
Expand file tree
/
Copy pathMedian.php
More file actions
34 lines (29 loc) · 796 Bytes
/
Copy pathMedian.php
File metadata and controls
34 lines (29 loc) · 796 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<?php
declare(strict_types=1);
/**
* This function calculates
* The median value of
* numbers provided
*
* @param float|int $numbers A variable sized number input
* @return float|int $median Median of provided numbers
* @throws \Exception
*/
function median(...$numbers): float|int
{
if ($numbers === []) {
throw new \Exception('Please pass values to find mean value');
}
foreach ($numbers as $number) {
if (!is_numeric($number)) {
throw new \Exception('Please pass numeric values to find median value');
}
}
sort($numbers);
$length = count($numbers);
$middle = intdiv($length, 2);
if ($length % 2 == 0) {
return ($numbers[$middle] + $numbers[$middle - 1]) / 2;
}
return $numbers[$middle] + 0;
}