Help for avoiding undefined index notices

If you are just starting out with PHP, you may come across this message:

Notice: Undefined index: username in C:\wamp\www\mysite\index.php on line 99

Even if you’ve been coding for years you can still get this message!

You may be confused as to what an “Undefined index” is? Often seen when trying to access global server variables such as $_POST and $_GET when passing data from another page or posting it back to the same page.

So what is it? It really is an index of an array that hasn’t been defined yet.  You are trying to access data in a variable that doesn’t exist!

Depending on the PHP error reporting level you configure, you can even hide these notices, but that’s not recommended, better to deal with them and write good code.

You can normally fix your “Undefined index” errors with the isset function to check whether a variable is set, like this:

// Check if the username is set or not...
If (isset($_POST['username']))
{
$username = $_POST['username'];
}
else
{
$username = "";
}

However a very useful function which can save you many lines of code like the above and undefined index notices, can be found in the comments (all credit to the author) on the same page of the PHP manual.

function isset_or(&$check, $alternate = NULL)
{
return (isset($check)) ? $check : $alternate;
}

//Example usage which will give the same result as the if / else statement above
$username = isset_or($_POST['username'], "");

It’s a very useful function if you are using plain PHP and need to determine the value of variables. It will also make your code cleaner and easier to read than repeated if / else statements like the above.

Leave a Reply