How to solve undefined offset notice in PHP

Posted on Nov 21, 2022

See how you can fix the undefined offset notice message when coding PHP apps

The PHP “undefined offset” notice occurs when you try to access an array element that doesn’t exist.

For example, suppose you have a non-associative array with one element as shown below:


$arr = ["Jack"];

print $arr[0]; // Jack
print $arr[1]; // Notice: Undefined offset

When you try to access an element using its number key, PHP will check if the key is defined in your array.

In the above example, the key [1] doesn’t exist in the $arr variable, which is why PHP responded with “Notice: Undefined offset” message.

To fix this message, you need to make sure that you are accessing an array element that exists in your array.

You can write an if statement that checks whether the array key and element exist using the isset() function as shown below:


$arr = ["Jack"];

if (isset($arr[1])) {
    print $arr[1];
} else {
    print "Array key [1] is undefined";

// Output: Array key [1] is undefined

By calling the isset() function to check on the $arr[1] variable, the “undefined offset” message won’t be shown.

The else statement allows PHP to gracefully notifies you that the array key is undefined.

Now you’ve learned how to solve the undefined offset message in PHP. Good work!

Level up your programming skills

I'm sending out an occasional email with the latest programming tutorials. Drop your email in the box below and I'll send new stuff straight into your inbox!

No spam. Unsubscribe anytime.