How to Fix PHP Notice: Undefined index?

Ever struggled hours and hours to figure out a fix for this notice?

undefined-index-4886632

First of all let us understand the problem.It should be clearly understood that this is NOT an ‘Error’, but a ‘Notice’. A notice can be ignored if it’s not critical while an error must be fixed. You might have observed that even though a notice appears, rest of the output will be displayed on the browser.

Coming back to our topic, when the ‘Undefined index’ notice occurs, most of the time it is a good practice to fix this than ignoring.

How to Fix

One simple answer – isset() !

isset() function in PHP determines whether a variable is set and is not NULL. It returns a Boolean value, that is, if the variable is set it will return true and if the variable value is null it will return false.

More details on this function can be found in PHP Manual.

Example

Let us consider an example.

Below is the HTML code for a comment form in a blog.

    

Please leave a comment:

    

Enter Comment


Notify me when a new post is published.

Here is the PHP file ‘add_comment.php’ which takes the data passed from the comment form.

What happens is, when the check-box is CHECKED, the code works fine. But when it is not, then I am getting the warning as mentioned above.

Warning: Undefined index:

So to fix this, let us make use of the magic function. Now the code appears like this.

What happens here is, I am checking first whether the check box is CHECKED (or set) using a condition. And if the condition is true I am getting the value passed.

The same fix can be used for the above warning when working with $_SESSION, $_POST arrays.

But, there instances where harmless notices can be ignored.

For an example,

I have a page which can be accesses in below 3 ways.

www.someexample.com/comments.php

www.someexample.come/comments.php?action=add

www.someexample.com/comments.php?action=delete

All these URL’s go to the same page but each time performs a different task.

So when I try to access the page through the first URL, it will give me the ‘Undefined index’ notice since the parameter ‘action’ is not set.

We can fix this using the isset() function too. But on this instance, we can just ignore it by hiding the notices like this.

error_reporting(E_ALL ^ E_NOTICE);

You can also turn off error reporting in your php.ini file or .htaccess file, but it is not considered as a wise move if you are still in the testing stage.

This is another simple solution in PHP for a common complex problem. Hope it is useful.

Tags: #PHP