Notice: Undefined offset
This error means that within your code, there is an array and its keys. But you may be trying to use the key of an array which is not set.
The error can be avoided by using the isset() method. This method will check whether the declared array key has null value or not. If it does it returns false else it returns true for all cases.
This type of error occurs with arrays when we use the key of an array, which is not set.
In the following, given an example, we are displaying the value store in array key 1, but we did not set while declaring array “$colorarray.”
Error Example:
<?php
// Declare an array with key 2, 3, 4, 5
$colorarray = array(2=>'Red',3=>'Green',4=>'Blue',5=>'Yellow');
// Printing the value of array at offset 1.
echo $colorarray[1];
?>
Output:
Notice: Undefined offset: 1 in \index.php on line 5
Here are two ways to deal with such notices.
- Resolve such notices.
- Ignore such notices.
Fix Notice: Undefined offset by using isset() Function
Check the value of offset array with function isset(), empty(), and array_key_exists() to check if key exist or not.
Example:
<?php
$colorarray = array(2=>'Red',3=>'Green',4=>'Blue',5=>'Yellow');
// isset() function to check value at offset 1 of array
if(isset($colorarray[1])){echo $colorarray[1];}
// empty() function to check value at offset 1 of array
if(!empty($colorarray[1])){echo $colorarray[1];}
// array_key_exists() of check if key 1 is exist or not
echo array_key_exists(1, $colorarray);
?>
How to Ignore PHP Notice: Undefined offset?
You can ignore this notice by disabling reporting of notice with option error_reporting.
1. Disable Display Notice in php.ini file
Open php.ini file in your favourite editor and search for text “error_reporting” the default value is E_ALL. You can change it to E_ALL & ~E_NOTICE.
By default:
error_reporting = E_ALL
Change it to:
error_reporting = E_ALL & ~E_NOTICE
Now your PHP compiler will show all errors except 'Notice.'
2. Disable Display Notice in PHP Code
If you don’t have access to make changes in the php.ini file, In this case, you need to disable the notice by adding the following code on the top of your php page.
<?php error_reporting (E_ALL ^ E_NOTICE); ?>
Now your PHP compiler will show all errors except 'Notice.'