"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP

Nadia S.

The Problem

You’re getting one or more of the following PHP “undefined” runtime messages:

  • “Notice: Undefined variable”
  • “Notice: Undefined index”
  • “Warning: Undefined array key”
  • “Notice: Undefined offset”

What do these error messages mean and how do you stop them from occurring?

The Solution

The benefit of these “undefined” errors is to draw attention to problems that you may not have anticipated.

These “undefined” messages indicate that a variable or array key was not defined before an attempt to use it was made. These are useful messages that alert you to a syntax error or a break in the smooth data flow in your code, so it’s good practice to address the issues they raise rather than suppress or circumvent them.

We’ll take a look at what “undefined” messages tell us and how to resolve the problems they report. We’ll also show you how to stop warnings and notices from being displayed, but this is not a recommended approach to dealing with error messages.

Notice: Undefined variable

Variables in PHP don’t have to be initialized but the PHP documentation recommends that you do. Initialize variables according to the data type they hold:

  • Integers to 0.
  • Booleans to false.
  • Strings to an empty string ''.
  • Arrays to an empty array [].

For example:

Click to Copy
$myNum = 0; $myText = ''; $myBoolean = false; $myArray = []; // display initialized values echo $myNum .PHP_EOL; echo $myText .PHP_EOL; echo $myBoolean .PHP_EOL; // 'false' returns an empty string print_r($myArray); // variable name typo echo $myTxet;

Note that in PHP, false returns an empty string, and true returns a value of 1.

When we run this script, we get the “Warning: Undefined variable” error because of the misspelled $myTxet variable name:

Click to Copy
0 Array() Warning: Undefined variable $myTxet in ../var/www/index.php on line 14

The benefits of initializing variables are that you can be certain that a variable holds the intended value and your code is easier to understand and fix.

To circumvent the “Undefined variable” notice, use the null coalescing operator (??) to assign a default value when the value is null. For example, to assign an empty string to the undeclared and uninitialized $value variable:

Click to Copy
// empty string as a default value echo $value ?? '';

Warning: Undefined array key

As from PHP 8, the “Undefined array key” warning replaces both the “Undefined offset” and “Undefined index” notices from previous versions.

The “Undefined array key” warning tells you that your code refers to an array key without a value.

For example, the age key doesn’t exist in the following employee array:

Click to Copy
$employee = ['firstName' => 'John', 'lastName' => 'Doe']; echo $employee['age'];

Output:

Click to Copy
Warning: Undefined array key "age" in ../var/www/index.php on line 3

To fix this, you can define an array key by initializing its value when you use it. For example:

Click to Copy
$employee['age'] = 0; echo $employee['age'];

Output:

Click to Copy
0

However, make sure that the data flow of your script or app is working as expected. For example, check that initialized keys are being updated later in your code if you need them to be.

If you’re working with external arrays, such as $_SERVER or $_POST superglobal variables, you can prevent “undefined” notices by checking if a value exists before using it. Use either the isset() function or the empty() function with the logical NOT operator (!) to check if a value exists. For example:

Click to Copy
if (isset($employee['age'])) { echo $employee['age']; } if (!empty($employee['age'])) { echo $employee['age']; }

Notice: Undefined index

In PHP versions before 8.2, the “Undefined index” notice occurs when you use a string array key that doesn’t have a value assigned to it. This can happen if you misspell a key, which therefore doesn’t exist. For example,

Click to Copy
$employee = ['firstName' => 'John', 'lastName' => 'Doe']; echo $employee['fristName'];

Output:

Click to Copy
Notice: Undefined index: fristName in ../var/www/index.php on line 3

To fix this problem, look at your data flow to ensure that array values are populated before use.

In the case of superglobal variables, we can get the “Undefined index” notice when our code refers to a key that doesn’t hold a value. For example, if we attempt to echo out the client IP address of a shared network when none is in use:

Click to Copy
echo $_SERVER['HTTP_CLIENT_IP'];

Output:

Click to Copy
Notice: Undefined index: HTTP_CLIENT_IP in ../var/www/index.php on line 16

You can solve this problem by checking whether the value exists before using it. Use the isset() function or the empty() function with the logical NOT operator (!) to check whether the value exists. For example:

Click to Copy
// using the `isset()` function if(isset($_SERVER['HTTP_CLIENT_IP'])) { echo $_SERVER['HTTP_CLIENT_IP']; } // using `!` with the `empty()` function if(!empty($_SERVER['HTTP_CLIENT_IP'])) { echo $_SERVER['HTTP_CLIENT_IP']; }

Notice: Undefined offset

In PHP versions below 8, the “Undefined offset” notice is given when you try to access an array element with an invalid index, that is, the index is outside the bounds of the array.

One way you can prevent accessing an element with an invalid index is to use the isset() function in an if statement to check if the element at a given index exists.

Click to Copy
$myArray = ['apple', 'banana', 'orange']; if (isset($myArray[3])) { echo $myArray[3]; }

Alternatively, if you’re working with numeric keys, you can use the count() function to find the length of the array and then use numeric keys in that range. For example, we can access the value of the last element by subtracting the length of the array by 1.

Click to Copy
$myArray = ['apple', 'banana', 'orange']; echo $myArray[count($myArray) - 1];

Output:

Click to Copy
orange

Turn off error reporting

You can remove notices and warnings by adding error_reporting(E_ERROR | E_PARSE); to the top of your PHP script, but this approach isn’t recommended as it makes it harder to identify and fix problems. Addressing the problems that lead to notices and warnings will improve the robustness and quality of your code.

Loved by over 4 million developers and more than 90,000 organizations worldwide, Sentry provides code-level observability to many of the world’s best-known companies like Disney, Peloton, Cloudflare, Eventbrite, Slack, Supercell, and Rockstar Games. Each month we process billions of exceptions from the most popular products on the internet.

Share on Twitter
Bookmark this page
Ask a questionJoin the discussion

Related Answers

A better experience for your users. An easier life for your developers.

    TwitterGitHubDribbbleLinkedinDiscord
© 2024 • Sentry is a registered Trademark
of Functional Software, Inc.