- var_export: documentation ( source)
- sort: documentation ( source)
<?php
class MyMath
{
/**
* @throws Exception
*/
public function calculateMedian(array $array): int|float
{
if (!$array) {
throw new LengthException('Cannot calculate median because Argument #1 ($array) is empty');
}
sort($array);
$middleIndex = count($array) / 2;
if (is_float($middleIndex)) {
return $array[(int) $middleIndex];
}
return ($array[$middleIndex] + $array[$middleIndex - 1]) / 2;
}
}
$math = new MyMath;
var_export($math->calculateMedian([1, 2, 3, 4, 5]));