PHP Notice: Undefined index

Have you ever gotten this error:
Notice: Undefined index ‘fields of the table’ in ‘path of the PHP file you’re executing’ on line ‘the current linenumber’ ? I think you do, since most probably, Google or Bing or so have lead you to this post because you were searching for a solution for that very errormessage 🙂
Well, you get this error when you are using variables in an array, but the “index” is not set.
An array is basically a “group” of keys and values put together in one variable, and can be used with that variable’s name, and the index (or key) you are refering to. For instance:

“value1”,
“key2” => “value2”,
“key3” => “value3”
);

// Or the same array can be written as such:
$MyArray = [
“key1” => “value1”,
“key2” => “value2”,
“key3” => “value3”
];
?>

If you need the value of key2, you will refer to it as:


$MyArray[“key2”];

Now, if you do not use a “key” while assigning values to your array, PHP will define the keys by itself, in an ordered numerical list, starting from “0”, resulting in this:


Quite a common reason to get this error is when using $_POST or $_GET arrays to retrieve the data from a form, and the variables are not set.

To get rid of this error, it is sufficient to test if the field of the table (so, the array) was initialized with the function isset ().

// Check this before you start using your $_POST[‘value’] variable
if (isset($_POST[‘value’]))
{
// Use and abuse your $_POST[‘value’] here!
}

Another way to get rid of this message, is by changing the configuration of your Apache/PHP setup. The error above is considered a minor error, corresponding to the constant E_NOTICE, and thus not shown in the standard configuration. But be warned, this doesn’t FIX the problem, it only stops showing it to you.
You can set your error reporting level in your PHP scripts with the error_reporting function, and by using these constants:
E_WARNING     Non-fatal run-time errors. Execution of the script is not halted
E_NOTICE     Run-time notices. The script found something that might be an error, but could also happen when running a script normally
E_RECOVERABLE_ERROR     Catchable fatal error. This is like an E_ERROR but can be caught by a user defined handle
E_ALL
Errorlevels can be combined in the error_reporting function such as E_ALL^E_NOTICE, which would show all errors, except Notices.

Leave a Comment





%d bloggers like this: