"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP
Nadia S.
—You’re getting one or more of the following PHP “undefined” runtime messages:
What do these error messages mean and how do you stop them from occurring?
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.
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:
0
.false
.''
.[]
. For example:
$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:
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:
// empty string as a default value echo $value ?? '';
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:
$employee = ['firstName' => 'John', 'lastName' => 'Doe']; echo $employee['age'];
Output:
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:
$employee['age'] = 0; echo $employee['age'];
Output:
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:
if (isset($employee['age'])) { echo $employee['age']; } if (!empty($employee['age'])) { echo $employee['age']; }
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,
$employee = ['firstName' => 'John', 'lastName' => 'Doe']; echo $employee['fristName'];
Output:
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:
echo $_SERVER['HTTP_CLIENT_IP'];
Output:
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:
// 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']; }
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.
$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
.
$myArray = ['apple', 'banana', 'orange']; echo $myArray[count($myArray) - 1];
Output:
orange
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.
Tasty treats for web developers brought to you by Sentry. Get tips and tricks from Wes Bos and Scott Tolinski.
SEE EPISODESConsidered “not bad” by 4 million developers and more than 100,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.
Here’s a quick look at how Sentry handles your personal information (PII).
×We collect PII about people browsing our website, users of the Sentry service, prospective customers, and people who otherwise interact with us.
What if my PII is included in data sent to Sentry by a Sentry customer (e.g., someone using Sentry to monitor their app)? In this case you have to contact the Sentry customer (e.g., the maker of the app). We do not control the data that is sent to us through the Sentry service for the purposes of application monitoring.
Am I included?We may disclose your PII to the following type of recipients:
You may have the following rights related to your PII:
If you have any questions or concerns about your privacy at Sentry, please email us at [email protected].
If you are a California resident, see our Supplemental notice.