When working with PHP, there is no doubt that at some point in your coding journey, you've experienced the undefined array key warning in PHP. But what does it mean and how can it be prevented? We will explore why it occurs and how we can amend our code to avoid filling up our PHP error logs with such warnings. With easy-to-follow PHP code examples shown along the way, let's explore how to prevent the PHP warning undefined array key.
Have you ever seen this PHP warning in your logs; "Warning: Undefined array key x in y"? Let's find out why this might occur and inspect what's going on. In the following example, when attempting to echo key '3' from our array, PHP triggers an Undefined array key 3. If we take a look at the array, it only contains two elements. First being at position 0 and the second being at position 1. Remember in PHP, arrays are zero-based, meaning they start from zero, not 1. Because what we're attempting to do here, could be considered as a potential to cause an unwanted bug, PHP rightly throws a warning.
# A simple array with two elements
$array = [0 => 'A', 1 => 'B'];
# Warning: Undefined array key 3
echo $array[3];
If you don't see this error in your PHP script, try adding the following line to your script. This changes the error reporting level at runtime, of which '-1' is to report everything that is listed in PHP's error constants.
error_reporting(-1);
How to fix Undefined array key error in PHP
One way to avoid the undefined array key error is to check that the key exists using the 'isset' function. This checks if the given array key exists in the array. In the code example below, if it does it will echo it, otherwise, nothing will happen, not even a PHP warning, phew!
# A simple array with two elements
$array = [0 => 'A', 1 => 'B'];
# Wrap with isset() function
if (isset($array[3])) {
echo $array[3];
}
This error doesn't just trigger when attempting to access an array's key with an index. In an associative array, this can happen too. Associative arrays are arrays whose keys are strings and not indexes. Let's take a look at the following example, where we attempt to echo the value of key "test" on an associative array where the key does not exist, therefore PHP triggers an undefined warning.
# A simple array with two elements
$array = ['hello' => 'abc', 'world' => 'xyz'];
# Warning: Undefined array key "test"
echo $array['test'];
An alternative to using the 'isset' function is to use 'array_key_exists', to check the value before attempting to use it. It works in a similar way, returning either true or false, and is great for associative arrays like this one.
# A simple array with two elements
$array = ['hello' => 'abc', 'world' => 'xyz'];
# Alertnative too isset(), is the array_key_exists() function
if (array_key_exists('test', $array)) {
echo $array['test'];
}
This error can also occur when using other pre-built PHP functions, like explode. Here, we're exploding out the string on a dot, into an array of items, of which key '3', doesn't exist.
# Using explode(), explode string on "." (dot).
$findString = explode('.','A.B.C');
# $findString would look like this
Array
(
[0] => A
[1] => B
[2] => C
)
# Warning: Undefined array key 3
echo $findString[3];
The same can happen with preg_match_all, where in the example below, we are using regex to find all letters between A and Z. We should find some matches, which will be, 'a, b, and c'. As there are only three (which is index two in the array), array key 5 doesn't exist, therefore would error.
# This matches all a-z characters
preg_match_all('/[a-z]/', '1 a 2 b 3 c 4', $matches);
print_r($matches);
# $matches would look like this
Array
(
[0] => Array
(
[0] => a
[1] => b
[2] => c
)
)
# Warning: Undefined array key 5
echo $matches[5];
Another area that is common for the undefined array key error in PHP is sessions. As PHP sessions are secure, we know the information isn't getting exposed to the user within the cookie, but within the code, we might want to do something with the data, as a PHP session is by default an array. In the example, we get an undefined array key in PHP's session because the key doesn't exist. This will trigger in all versions of PHP, including PHP 8.0, 8.1, and 8.2+.
# Start the session
session_start();
# Warning: Undefined array key "user"
$_SESSION['user'];
When accepting user data, it's common for this to occur if you expect certain data to arrive at your server but validation hasn't occurred, therefore triggering the error. This can happen on '$_REQUEST', '$_GET', '$_POST', or '$_FILES'. This could also trigger the error if doing a POST request with Ajax. When working with any user input data, it's always good to check they exist and escape the data before using them in your web application, particularly when saving to a database or displaying back to a user on the front end.
# Warning: Undefined array key "id"
echo $_REQUEST['id'];
Another cause for this trigger could be when working with PHP authentication, typically in line with an API service. Using HTTP authentication with PHP, it uses the '$_SERVER' array variable. Inside this is 'PHP_AUTH_USER' and 'PHP_AUTH_PW'. But if a user fails to populate one or both of these, a PHP warning will be triggered. To fix the undefined array keys php_auth_user and php_auth_pw, make sure to check they exist before attempting to use them.
# Warning: Undefined array key "PHP_AUTH_USER"
echo $_REQUEST['PHP_AUTH_USER'];
# Warning: Undefined array key "PHP_AUTH_PW"
echo $_REQUEST['PHP_AUTH_PW'];
Conclusion
When working with different variables in PHP, especially those that are of type array, be sure to check the key, either index or string exists before attempting to use it.
- Use isset() or array_key_exists() function to check the key exists in the array before using it
- Remember it can occur in other areas of PHP, such as session, server, get, post, preg_match_all functions within PHP
- Setting the error reporting level at run time can be a quick way to check for any "Undefined array key" errors.