[英]I'm receiving Undefined offset error
为什么我会收到Undefined offset error
? 我正在尝试为数组中的每个元素添加10,20,20
。 请帮忙。 提前致谢
<?php
$arr = array("a","b","c");
$counter = 0;
$status = array();
foreach($arr as $a){
$status[$counter] += 10;
$status[$counter] += 20;
$status[$counter] += 20;
echo $status[$counter]."<br>";
$counter ++;
}
?>
错误:
Notice: Undefined offset: 0 in C:\xampp\htdocs\test\index.php on line 6
300
Notice: Undefined offset: 1 in C:\xampp\htdocs\test\index.php on line 6
300
Notice: Undefined offset: 2 in C:\xampp\htdocs\test\index.php on line 6
300
`
您试图在此行的未定义数组元素中添加 10:
$status[$counter] += 10;
试试这样:
$arr = array("a","b","c");
$counter = 0;
$status = array();
foreach($arr as $a){
$status[$counter] = 10;//assign first
$status[$counter] += 20; //concate with assigned element
$status[$counter] += 20;
echo $status[$counter]."<br>";
$counter ++;
}
它不应提供任何通知。
在您的代码中, $status
是一个空数组,因此当您尝试向未定义的索引添加内容时,您将看到该通知(仅第一次)。
根据$arr
的元素数将$status
初始化$status
值为 0 的数组:
$status = array_fill(0, count($arr), 0);
您正在使用“添加和分配”运算符。
如果你只想赋值,那么
$status[$counter] = 10;
会工作得很好。
但是,您要求 PHP 向数组中的现有元素添加一些内容,但由于您尚未对其进行初始化,因此那里还没有任何元素。 只需在开始循环之前初始化您的数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.