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

发布于 2024-11-19 20:51:53 字数 335 浏览 3 评论 0原文

我不确定为什么我会收到关于此的未定义偏移通知

<?php 

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

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

?>

输出:

136 注意:未定义的偏移量:3 位于 E:\php\arrays\array_1.php 第 17 行 6

I'm not sure why I am getting an Undefined Offset Notice on 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 17
6

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

败给现实 2024-11-26 20:51:53

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

您的循环应该在遇到该元素之前停止...

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

另外,请检查 array_sum,这可能就是你想要的......

$total=array_sum($numbers);

Your array has three elements at index 0, 1 and 2. There is no element with index 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...

$total=array_sum($numbers);
噩梦成真你也成魔 2024-11-26 20:51:53

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

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

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

for($i=0;$i<sizeof($numbers); $i++) {
木有鱼丸 2024-11-26 20:51:53

将条件从 <= 更改为 <

这将正确添加:

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

Change your condition from <= to <.

This will add properly:

$total += intval($numbers[$i]);
掩耳倾听 2024-11-26 20:51:53

关闭 html 错误

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

turnoff html errors

error_reporting(E_ALL);
ini_set('display_errors', 'On');
ini_set('html_errors', 'Off'); 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文