[php] 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?

This question is related to php error-handling syntax-error undefined fatal-error

The answer is


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;

How to reproduce the above error in 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 1 and ran the hash against it and didn't find any value associated with it then said 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


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!

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

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

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.


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.


Hide php warnings in file

error_reporting(0);

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 ","...


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

  $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 140 but after using the minus 1 everything was fine


Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to error-handling

must declare a named package eclipse because this compilation unit is associated to the named module Error:Failed to open zip file. Gradle's dependency cache may be corrupt What does 'index 0 is out of bounds for axis 0 with size 0' mean? What's the source of Error: getaddrinfo EAI_AGAIN? Error handling with try and catch in Laravel What does "Fatal error: Unexpectedly found nil while unwrapping an Optional value" mean? Raise error in a Bash script Javascript Uncaught TypeError: Cannot read property '0' of undefined Multiple values in single-value context IndexError: too many indices for array

Examples related to syntax-error

Uncaught SyntaxError: Unexpected token u in JSON at position 0 How to solve SyntaxError on autogenerated manage.py? Checking whether the pip is installed? (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape How can you print multiple variables inside a string using printf? Unexpected token < in first line of HTML Laravel: Error [PDOException]: Could not Find Driver in PostgreSQL 'Syntax Error: invalid syntax' for no apparent reason How can I fix MySQL error #1064? Notice: Trying to get property of non-object error

Examples related to undefined

Checking for Undefined In React Raw_Input() Is Not Defined How to resolve TypeError: Cannot convert undefined or null to object "undefined" function declared in another file? Passing Variable through JavaScript from one html page to another page Javascript - removing undefined fields from an object PHP How to fix Notice: Undefined variable: Undefined Symbols for architecture x86_64: Compiling problems Undefined or null for AngularJS PHP Notice: Undefined offset: 1 with array when reading data

Examples related to fatal-error

Fatal error: Allowed memory size of 268435456 bytes exhausted (tried to allocate 71 bytes) PHP Notice: Undefined offset: 1 with array when reading data PHP Fatal error: Cannot access empty property PHP Fatal error when trying to access phpmyadmin mb_detect_encoding Fatal error: Class 'SoapClient' not found Cannot redeclare function php C++ Fatal Error LNK1120: 1 unresolved externals A fatal error has been detected by the Java Runtime Environment: SIGSEGV, libjvm Why, Fatal error: Class 'PHPUnit_Framework_TestCase' not found in ...? relative path in require_once doesn't work