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

前端 未结 10 1458
遇见更好的自我
遇见更好的自我 2020-12-04 15:14

I am getting this PHP error:

PHP Notice:  Undefined offset: 1

Here is the PHP code that throws it:

$file_handle = fopen($pa         


        
相关标签:
10条回答
  • 2020-12-04 15:56

    Update in 2020 in Php7:

    there is a better way to do this using the Null coalescing operator by just doing the following:

    $data[$parts[0]] = $parts[1] ?? null;
    
    0 讨论(0)
  • 2020-12-04 15:58

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

    $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!
    
    0 讨论(0)
  • 2020-12-04 15:59

    This is a "PHP Notice", so you could in theory ignore it. Change 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.

    0 讨论(0)
  • 2020-12-04 16:00

    In your code: $parts = array_map('trim', explode(':', $line_of_text, 2)); You have ":" as separator. If you use another separator in file, then you will get an "Undefined offset: 1" but not "Undefined offset: 0" All information will be in $parts[0] but no information in $parts[1] or [2] etc. Try to echo $part[0]; echo $part[1]; you will see the information.

    0 讨论(0)
提交回复
热议问题