Monday, September 28, 2015

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


I am getting this PHP error:
PHP Notice:  Undefined offset: 1
Here is the PHP code that throws it:
$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?
shareimprove this question
1 
How sure are you that every line in your file has a colon in it? –  andrewsi Jul 3 '13 at 19:16
   
do a var_dump($parts). you'll probably find that the point you get that undefined offset, there is no 1key in the parts array. –  Marc B Jul 3 '13 at 19:16
2 
If it looks like all the lines have a colon, check for blank lines. –  Barmar Jul 3 '13 at 19:18
   
you just need to make sure that count($parts) == 2 prior to doing your assignment. –  Orangepill Jul 3 '13 at 19:18 
   
@Orangepill You mean count($parts). –  Barmar Jul 3 '13 at 19:18

3 Answers

up vote28down voteaccepted
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."
shareimprove this http://stackoverflow.com/questions/17456325/php-notice-undefined-offset-1-with-array-when-reading-dataanswer