在尝试运行下面的代码时,我的浏览器一直在回应下面的错误。我如何修复下面的代码,以便这些错误不再出现?未定义的偏移量和未定义的变量问题
为了清楚起见,这些错误在包含线只出现在每个的下面:
$high = $arr[$middleval+1];
$median = (($low+$high)/2);
由于
代码:
function median($arr)
{
sort($arr);
$count = count($arr); //count the number of values in array
$middleval = floor(($count-1)/2); // find the middle value, or the lowest middle value
if ($count % 2) { // odd number, middle is the median
$median = $arr[$middleval];
} else { // even number, calculate avg of 2 medians
$low = $matches[0];
$high = $arr[$middleval+1];
$median = (($low+$high)/2);
}
return $median;
}
错误:
Notice: Undefined offset: 0 in medium.php on line 9
Notice: Undefined variable: matches in medium.php on line 10
代码中没有变量'$ matches',我没有看到如何得到第二个错误。 – Barmar
$ low = $ matches [0]; – user7644146
如果'$ arr'为空,则会出现此错误。 '$ count = 0',这是偶数,那么你尝试访问不存在的'$ arr [0]'。 – Barmar