2017-03-01 179 views
0

在尝试运行下面的代码时,我的浏览器一直在回应下面的错误。我如何修复下面的代码,以便这些错误不再出现?未定义的偏移量和未定义的变量问题

为了清楚起见,这些错误在包含线只出现在每个的下面:

$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

+0

代码中没有变量'$ matches',我没有看到如何得到第二个错误。 – Barmar

+0

$ low = $ matches [0]; – user7644146

+0

如果'$ arr'为空,则会出现此错误。 '$ count = 0',这是偶数,那么你尝试访问不存在的'$ arr [0]'。 – Barmar

回答

0

Undefined offset是一个超出界限的错误:您试图从不存在的数组中获取值。例如。如果您的阵列有两个值,在索引01$middleval等于1,$arr$middleval + 1处没有值,即未设置$arr[2]

第二个错误消息告诉您,您正尝试使用未定义的变量$matches。你可能想看看this code review answer

+0

我编辑了我的代码。道歉 – user7644146