PHP中计算数组相邻元素差时如何避免Undefined offset错误
解决PHP数组遍历中Undefined Offset错误的方案
你的错误根源是遍历到数组最后一个元素时,尝试访问$number[$counter+1],但这个索引不存在(数组共16个元素,索引范围是0-15,最后一次循环时$counter+1等于16,超出了数组的有效索引)。
以下是两种可行的修复方案:
方案一:使用for循环控制遍历范围
直接循环到数组的倒数第二个元素,避免处理最后一个无后续元素的项:
$number = array(179522, 179552, 179747, 179758, 179838, 179951, 179991, 180089, 180191, 180263, 180443, 180444, 180445, 180534, 180584, 180822 ); $two = 0; $one = 0; $sum = 0; // 循环到倒数第二个元素(索引为count($number)-2) for($counter = 0; $counter < count($number)-1; $counter++){ $item = $number[$counter] - $number[$counter+1]; if($item == -2) $two++; if($item == -1) $one++; } $sum = $one + $two; print_r("All: ".$sum."\n"); print_r("With -2: ".$two."\n"); print_r("With -1: ".$one."\n");
方案二:在foreach中添加存在性判断
保留foreach循环,但每次循环时检查下一个元素是否存在:
$number = array(179522, 179552, 179747, 179758, 179838, 179951, 179991, 180089, 180191, 180263, 180443, 180444, 180445, 180534, 180584, 180822 ); $two = 0; $one = 0; $sum = 0; foreach($number as $key => $row){ // 检查下一个索引是否存在 if(!isset($number[$key+1])){ break; } $item = $row - $number[$key+1]; if($item == -2) $two++; if($item == -1) $one++; } $sum = $one + $two; print_r("All: ".$sum."\n"); print_r("With -2: ".$two."\n"); print_r("With -1: ".$one."\n");
两种方案都能避免访问不存在的数组索引,解决Undefined Offset的报错问题,同时正确计算相邻元素的差值统计。
内容的提问来源于stack exchange,提问作者Mikasa
相关产品推荐
相关产品推荐

