-
Notifications
You must be signed in to change notification settings - Fork 8
/
median.php
45 lines (37 loc) · 848 Bytes
/
median.php
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
35
36
37
38
39
40
41
42
43
44
45
<?php
namespace Dash;
/**
* Returns the median value of an iterable.
*
* @param iterable|stdClass|null $iterable
* @return mixed|null Null if `$iterable` is empty
*
* @example
Dash\median([3, 2, 1, 5, 4]);
// === 3
Dash\median([3, 2, 1, 4]);
// === 2.5
*/
function median($iterable)
{
assertType($iterable, ['iterable', 'stdClass', 'null'], __FUNCTION__);
$size = size($iterable);
if ($size === 0) {
return null;
}
$sorted = values(sort($iterable));
if (isEven($size)) {
// For an even number of values,
// the median is the average of the middle two values
$start = $size / 2 - 1;
$end = $start + 1;
$median = ($sorted[$start] + $sorted[$end]) / 2;
}
else {
// For an odd number of values,
// the median is the middle value
$index = floor($size / 2);
$median = $sorted[$index];
}
return $median;
}