Why Does “Notice: Undefined Variable” or “Notice: Undefined index” all of a sudden show up in my PHP Code?

It’s a beautiful day, you make it to work and all of a sudden, out of no where, see PHP Notices like Notice: Undefined Variable, Notice: Undefined index, or Notice: Undefined offset. These errors might look something like the example below:

Notice: Undefined variable: variable_name in /index.php on line 3
Notice: Undefined index: index_name in /index.php on line 3
Notice: Undefined offset: 1 in /index.php on line 3

All of these are valid notices that PHP displays if there is a problem in your code. As it turns out, in PHP, a notice will not stop the rest of your code from executing. If your code is executing and working as expected, chances are, theses are just things you need to look into on why you are getting these notices.

The reason these started all of a sudden showing up is because your PHP application configuration has changed to allow notices to start displaying at runtime. This configuration can be turned on in several different ways. It can be configured in your php.ini or turned it can be turned on in your PHP code itself.

Turning Off PHP Notices

Turning off these notices is simple. You can do it right in your PHP code itself at the beginning of your script simply add error_reporting(0). Below is a list of values you can pass into the function for different levels of reporting.


// Turn off all error reporting

// Report simple running errors
error_reporting(E_ERROR | E_WARNING | E_PARSE);

// Reporting E_NOTICE can be good too (to report uninitialized
// variables or catch variable name misspellings ...)
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);

// Report all errors except E_NOTICE
error_reporting(E_ALL & ~E_NOTICE);

// Report all PHP errors (see changelog)

// Report all PHP errors

// Same as error_reporting(E_ALL);
ini_set('error_reporting', E_ALL);

Leave a Reply