简体   繁体   English

我收到未定义的偏移错误

[英]I'm receiving Undefined offset error

Why do I receive Undefined offset error ?为什么我会收到Undefined offset error I'm trying to add 10,20,20 for each element in array.我正在尝试为数组中的每个元素添加10,20,20 Please help.请帮忙。 Thanks in advance提前致谢

<?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 ++;
    }
?>

Error:错误:

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

` `

you are trying to add 10 in a undefined array element in this line:您试图在此行的未定义数组元素中添加 10:

$status[$counter] += 10;

try like this:试试这样:

  $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 ++; 
 }

it should not provide any notices.它不应提供任何通知。

In your code, $status is an empty array, so when you attempt to add something to an undefined index you will see that notice (only for the first time).在您的代码中, $status是一个空数组,因此当您尝试向未定义的索引添加内容时,您将看到该通知(仅第一次)。

To initialize $status as an array with values 0 based on the number of elements in $arr :根据$arr的元素数将$status初始化$status值为 0 的数组:

$status = array_fill(0, count($arr), 0);

You're using an 'add and assign' operator.您正在使用“添加和分配”运算符。

If you just want to assign a value then如果你只想赋值,那么

$status[$counter] = 10;

Will work just fine.会工作得很好。

However, you're asking PHP to add something to an existing element in your array, but there's no element there yet since you haven't initialised it.但是,您要求 PHP 向数组中的现有元素添加一些内容,但由于您尚未对其进行初始化,因此那里还没有任何元素。 Just initialise your array before you start your loop.只需在开始循环之前初始化您的数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM