php 注意:未定义偏移量:2
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15653119/
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
Notice: Undefined offset: 2
提问by Anuwa
I'm new to php and I have done an example in php book. In there I got below notice
. How to prevent this notice ?
我是 php 新手,我在 php 书中做了一个例子。在那里我得到了下面notice
。如何防止此通知?
<?php
require_once('AddingMachine.php');
$arrayofnumbers = array(100,200);
$objectname = new AddingMachine();
$objectname->addNumbers($arrayofnumbers);
?>
and
和
<?php
Class AddingMachine
{
private $total = 0;
function addNumbers(array $numbers)
{{
for($i=0;$i<=sizeof($numbers);$i++)
{
$this->total = $this->total + $numbers[$i];
}
echo $this->total;
}
}
}
回答by Rikesh
Change your loop from
改变你的循环
for($i=0; $i <= sizeof($numbers); $i++)
to
到
for($i=0; $i < sizeof($numbers); $i++)
Also preferable to use count
.
也最好使用count
.
for($i=0; $i < count($numbers); $i++)
回答by ATaylor
The problem is with the <= sizeof($numbers)
(which is equal to count($numbers)
. It will give you the total count of array elements, which is always one more than the maximum index, because arrays begin counting at 0.
问题在于<= sizeof($numbers)
( 等于count($numbers)
。它会给你数组元素的总数,它总是比最大索引多 1,因为数组从 0 开始计数。
Simply replace the <=
with <
and you'll be fine.
只需更换<=
用<
,你会没事的。