Avoiding undefined index / offset errors in PHP

This is a small guide on how to “fix” undefined index / offset errors in PHP.

What is an index?

Firstly, you need to understand what an index is. When an element is added to an array, it is given an index (you can set this manually or PHP will automatically set one for you). This index acts as an identifier that allows you to interact with the element in question. Without array indexes, you would be unable to keep track of which element is which.

For example, in PHP, I can create an array like so:

As you can see, Cat has the index “0” and Dog has the index “1“. If I want to print the word “Cat” out onto the page, I will need to access the “Cat” element via its array index:

As you can see, I specified the index “0” because that is is the index that “Cat” is “filed under”.

In a similar vein, if I want to print out the word “Dog”, I can access it via the index “1”:

If I want to delete the “Dog” element from our PHP array, I specify the array index like so:

unset will remove / destroy the element in question. This means that it will be no longer accessible.

What if I try to access an array index that does not exist?

This is where you’ll encounter nasty errors such as:

… Or, if you’re using array keys instead of numerical indexes:

These notices will occur whenever you attempt to access an index that does not exist! Although the execution of your script will not be halted (it is not a fatal error), these kind of notices tend to cause bugs that can lead to other issues!

$_POST, $_GET, $_SESSION

A lot of beginner PHP developers fail to realize that $_POST, $_GET, $_SESSION, $_FILES, $_COOKIE, $_SERVER and $_REQUEST are predefined arrays! i.e. They exist by default and they should be treated like regular arrays. When you access a GET variable in PHP, what you’re actually doing is accessing a GET variable that has been neatly packaged into an array called $_GET.

In the above piece of code, you are accessing an array element with the index “test”.

Avoiding Index Errors.

To avoid index / offset errors, you can use two different methods. The first method involves the isset function, which checks to see if a particular variable exists:

The second method involves the function array_key_exists, which checks to see if a particular index exists:

Remember: When dealing with $_POST and $_GET variables, you should always prove that the key exists before you attempt to access it!

Comments

comments