php 简单函数中的未定义偏移量()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6697899/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 01:01:40  来源:igfitidea点击:

php Undefined Offset in simple function()

phparraysfor-loopsizeof

提问by OldWest

I'm not sure why I am getting an Undefined Offset Noticeon this:

我不知道为什么我会收到一个未定义的偏移通知

<?php 

$numbers = array('1','2','3');
$total = 0;

for($i=0;$i<=sizeof($numbers); $i++) {
    $total += $numbers[$i];
    echo $total;
}

?>

Output:

输出:

136 Notice: Undefined offset: 3 in E:\php\arrays\array_1.php on line 176

136 注意:未定义的偏移量:3 in E:\php\arrays\array_1.php on line 176

回答by Paul Dixon

Your array has three elements at index 0, 1 and 2. There is no element with index 3.

您的数组在索引 0、1 和 2 处有三个元素。没有索引为 3 的元素。

Your loop should stop before it hits that...

你的循环应该在它到达之前停止......

for($i=0;$i<sizeof($numbers); $i++) {
}

Also, checkout array_sum, which might be what you're wanting anyway...

此外,结帐array_sum,这可能是你想要的东西......

$total=array_sum($numbers);

回答by Dogbert

You should loop to <the size of the array, not <=.

您应该循环到<数组的大小,而不是<=.

for($i=0;$i<sizeof($numbers); $i++) {

回答by wanovak

Change your condition from <=to <.

将您的条件从 更改<=<

This will add properly:

这将正确添加:

$total += intval($numbers[$i]);

回答by Vaibs

turnoff html errors

关闭 html 错误

error_reporting(E_ALL);
ini_set('display_errors', 'On');
ini_set('html_errors', 'Off');