PHP 注意:未定义偏移量:1 读取数据时带数组

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

PHP Notice: Undefined offset: 1 with array when reading data

phperror-handlingsyntax-errorundefinedfatal-error

提问by alchuang

I am getting this PHP error:

我收到此 PHP 错误:

PHP Notice:  Undefined offset: 1

Here is the PHP code that throws it:

这是抛出它的PHP代码:

$file_handle = fopen($path."/Summary/data.txt","r"); //open text file
$data = array(); // create new array map

while (!feof($file_handle) ) {
    $line_of_text = fgets($file_handle); // read in each line
    $parts = array_map('trim', explode(':', $line_of_text, 2)); 
    // separates line_of_text by ':' trim strings for extra space
    $data[$parts[0]] = $parts[1]; 
    // map the resulting parts into array 
    //$results('NAME_BEFORE_:') = VALUE_AFTER_:
}

What does this error mean? What causes this error?

这个错误是什么意思?是什么导致了这个错误?

回答by GGio

Change

改变

$data[$parts[0]] = $parts[1];

to

if ( ! isset($parts[1])) {
   $parts[1] = null;
}

$data[$parts[0]] = $parts[1];

or simply:

或者干脆:

$data[$parts[0]] = isset($parts[1]) ? $parts[1] : null;

Not every line of your file has a colon in it and therefore explode on it returns an array of size 1.

并非文件的每一行都有一个冒号,因此在它上面爆炸会返回一个大小为 1 的数组。

According to php.net possible return values from explode:

根据php.net 可能从爆炸返回值

Returns an array of strings created by splitting the string parameter on boundaries formed by the delimiter.

If delimiter is an empty string (""), explode() will return FALSE. If delimiter contains a value that is not contained in string and a negative limit is used, then an empty array will be returned, otherwise an array containing string will be returned.

返回通过在分隔符形成的边界上拆分字符串参数创建的字符串数组。

如果分隔符是空字符串 (""),explode() 将返回 FALSE。如果分隔符包含字符串中未包含的值并且使用负限制,则将返回一个空数组,否则将返回一个包含字符串的数组。

回答by Eric Leschinski

How to reproduce the above error in PHP:

如何在PHP中重现上述错误:

php> $yarr = array(3 => 'c', 4 => 'd');

php> echo $yarr[4];
d

php> echo $yarr[1];
PHP Notice:  Undefined offset: 1 in 
/usr/local/lib/python2.7/dist-packages/phpsh/phpsh.php(578) : 
eval()'d code on line 1

What does that error message mean?

该错误消息是什么意思?

It means the php compiler looked for the key 1and ran the hash against it and didn't find any value associated with it then said Undefined offset: 1

这意味着 php 编译器查找密钥1并对其运行散列,但没有找到任何与之关联的值,然后说Undefined offset: 1

How do I make that error go away?

我如何使该错误消失?

Ask the array if the key exists before returning its value like this:

在返回其值之前询问数组是否存在键,如下所示:

php> echo array_key_exists(1, $yarr);

php> echo array_key_exists(4, $yarr);
1

If the array does not contain your key, don't ask for its value. Although this solution makes double-work for your program to "check if it's there" and then "go get it".

如果数组不包含您的密钥,请不要询问其值。尽管此解决方案使您的程序“检查它是否在那里”然后“去获取它”进行了双重工作。

Alternative solution that's faster:

更快的替代解决方案:

If getting a missing key is an exceptional circumstance caused by an error, it's faster to just get the value (as in echo $yarr[1];), and catch that offset error and handle it like this: https://stackoverflow.com/a/5373824/445131

如果获取丢失的键是由错误引起的特殊情况,那么获取值(如 中所示echo $yarr[1];)会更快,并捕获偏移错误并像这样处理它:https: //stackoverflow.com/a/5373824/445131

回答by Orijmm

This is a "PHP Notice", so you could in theory ignore it. Change php.ini:

这是一个“PHP 通知”,因此理论上您可以忽略它。改变php.ini

error_reporting = E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED

To

error_reporting = E_ALL & ~E_NOTICE

This show all errors, except for notices.

这将显示所有错误,通知除外。

回答by Daniel Charles Mwangila

my quickest solution was to minus 1 to the length of the array as

我最快的解决方案是将数组的长度减 1 为

  $len = count($data);

    for($i=1; $i<=$len-1;$i++){
      echo $data[$i];
    }

my offset was always the last value if the count was 140 then it will say offset 140but after using the minus 1 everything was fine

如果计数为 140,我的偏移量始终是最后一个值,然后它会说,offset 140但在使用负 1 后一切都很好

回答by Sashi Giri

The ideal solution would be as below. You won't miss the values from 0 to n.

理想的解决方案如下。您不会错过从 0 到 n 的值。

$len=count($data);
for($i=0;$i<$len;$i++)
     echo $data[$i]. "<br>";

回答by Erikas

I just recently had this issue and I didn't even believe it was my mistype:

我最近才遇到这个问题,我什至不相信这是我的错误类型:

Array("Semester has been set as active!", true)
Array("Failed to set semester as active!". false)

And actually it was! I just accidentally typed "." rather than ","...

原来是这样!我只是不小心输入了“ .”而不是“ ”...

回答by Vitalicus

Hide php warnings in file

在文件中隐藏 php 警告

error_reporting(0);

回答by ZellaThor

The output of the error, is because you call an index of the Array that does not exist, for example

错误的输出,是因为您调用了不存在的 Array 的索引,例如

$arr = Array(1,2,3);
echo $arr[3]; 
// Error PHP Notice:  Undefined offset: 1 pointer 3 does not exist, the array only has 3 elements but starts at 0 to 2, not 3!