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

前端 未结 10 1527
遇见更好的自我
遇见更好的自我 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:38

    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.

    According to php.net possible return values from explode:

    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.

提交回复
热议问题