php 如何修复“未定义偏移”错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10356586/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to fix "Undefined offset" error
提问by Ash Davies
I'm trying to create a simple average calculator using an array with randomly generated numbers. I think the code is pretty solid but I'm being returned this error:
我正在尝试使用随机生成数字的数组创建一个简单的平均计算器。我认为代码非常可靠,但我收到了这个错误:
Notice: Undefined offset: 10 in ../average/averageresults.php on line 31
Line 31:
第 31 行:
for ($i=0; $i<=10; $i++) { echo $array[$i]."<br />"; }
Rest of code is as follows:
其余代码如下:
<?php
$array = array();
$array[]=rand(1, 99);
$array[]=rand(1, 99);
$array[]=rand(1, 99);
$array[]=rand(1, 99);
$array[]=rand(1, 99);
$array[]=rand(1, 99);
$array[]=rand(1, 99);
$array[]=rand(1, 99);
$array[]=rand(1, 99);
$array[]=rand(1, 99);
$i=0;
$sum = array_sum($array);
$count = count($array);
$avg = $sum/$count;
for ($i=0; $i<=10; $i++)
{
echo $array[$i]."<br />";
}
echo "The average of these numbers is: ".$avg;
?>
回答by Halcyon
You're "off by 1". The array has 10 elements, 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9. There is no 10.
你“差一分”。该数组有 10 个元素,0、1、2、3、4、5、6、7、8 和 9。没有 10。
Change your for loop to:
将您的 for 循环更改为:
for ($i=0; $i<10; $i++)"less than" instead of "less than or equals to"
for ($i=0; $i<10; $i++)“小于”而不是“小于或等于”

