簡體   English   中英

我收到未定義的偏移錯誤

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM