Use isset($array['key']) when a null value should count as missing, and array_key_exists('key', $array) when you need to know the key is there even if its value is null. To read a value with a fallback in one step, write $array['key'] ?? 'default'. Any of these avoids Warning: Undefined array key, which PHP 7 called Notice: Undefined index.
Reading a key that isn't there is one of the most common PHP messages: PHP 8 prints Warning: Undefined array key, gives you null, and keeps going. The fix is to check first, and PHP has two checks that disagree on one case: a key whose value is null. The sections below show isset and array_key_exists side by side, reading with a default using ?? and ??=, what the warning looks like and what it means, nested keys, why "1" and 1 are the same key, and checking for a value instead of a key, then a table to pick from. Each example runs on this page: hit Run, then edit the code and run it again.
1isset() vs array_key_exists()Recommended
array_key_exists($key, $array) answers exactly "is this key in the array?". isset($array[$key]) answers "is this key in the array and is its value not null?". For most data the two agree, and isset is shorter and accepts several keys at once. Speed is not a reason to pick either: on PHP 7.4 and later they take the same time. They part ways only on a null value, so pick array_key_exists when null means something, such as a database column that is present but empty. Note the argument order: key first, then the array.
<?php
$user = [
'name' => 'Ada',
'email' => null,
'admin' => false,
];
foreach (['name', 'email', 'admin', 'phone'] as $key) {
printf(
"%-5s array_key_exists: %-5s isset: %s\n",
$key,
var_export(array_key_exists($key, $user), true),
var_export(isset($user[$key]), true),
);
}
// isset takes several arguments: true only if every one is set
var_dump(isset($user['name'], $user['admin']));
var_dump(isset($user['name'], $user['email']));
Output
The only row where the two disagree is email: the key is there, so array_key_exists says true, but its value is null, so isset says false. admin holds false and is still set; only null makes isset return false, not 0, '' or false. With two arguments, isset returns bool(true) for name and admin and bool(false) as soon as one of them is email.
2Read with a default: ?? and ??=
Most of the time you check a key in order to read it. The null coalescing operator ?? (PHP 7.0) does both: $a['k'] ?? $default returns the value when the key exists and is not null, and the right side otherwise, with no warning. It behaves like isset, so a null value gets the default too. ??= (PHP 7.4) writes the default back into the array, but only when the key is missing or null. Don't confuse either with ?:, which replaces every falsy value.
<?php $config = ['host' => 'db.local', 'port' => null, 'debug' => false]; // ?? returns the right side when the key is missing or null $host = $config['host'] ?? 'localhost'; $port = $config['port'] ?? 5432; $user = $config['user'] ?? 'guest'; echo "$host:$port as $user\n"; // false is not null, so ?? keeps it; ?: replaces any falsy value var_dump($config['debug'] ?? true); var_dump($config['debug'] ?: 'fallback'); // Chain fallbacks: the first value that is set wins $timeout = $config['timeout'] ?? $config['default_timeout'] ?? 30; echo "timeout $timeout\n"; // ??= stores the default only where the key is missing or null $config['host'] ??= 'localhost'; $config['port'] ??= 3306; $config['retries'] ??= 3; echo json_encode($config), "\n"; // Before PHP 7.0: isset with a ternary $user = isset($config['user']) ? $config['user'] : 'guest'; echo $user, "\n";
Output
The first line, db.local:5432 as guest, shows both cases that fall back: port exists but is null, and user doesn't exist. $config['debug'] ?? true keeps the stored false, while ?: throws it away and returns "fallback", which is why ?? is the right tool for defaults. After the three ??= lines, host is unchanged, port became 3306 and retries was added. If a null value must stay null, test with array_key_exists instead.
3What reading a missing key does
Reading $array['key'] without a check doesn't stop the script. PHP 8 prints a warning, returns null, and runs the next line. That is where the famous messages come from. In PHP 7 the same reads were notices with different text: Notice: Undefined index: age for a string key, Notice: Undefined offset: 3 for an integer key and Notice: Undefined variable: city for a variable. PHP 8.0 raised them to warnings and renamed the first two to one message. Run this one and look at the error output: the warnings are expected here.
<?php $user = ['name' => 'Ada']; $scores = [10, 20, 30]; $age = $user['age']; // missing string key var_dump($age); $fourth = $scores[3]; // missing integer key var_dump($fourth); var_dump($city); // a variable that was never set echo "Still running\n";
Output
The output panel shows NULL three times and Still running, and the run exits with code 0. The error output carries the three warnings: Warning: Undefined array key "age" in /tmp/workspace/main.php on line 6, Warning: Undefined array key 3 (the key is printed without quotes because it is an integer) and Warning: Undefined variable $city. Treat them as bugs, not noise: a missing key that is normal belongs behind isset, array_key_exists or ??. Hiding the message with @$user['age'] still returns NULL but also hides the real typos.
4Nested keys
For nested arrays, such as decoded JSON, isset and ?? are the safe choice: they check every level from left to right and stop at the first one that is missing or null, without a warning. A plain read of $order['shipping']['city'] would warn twice: once for the missing key and once with Warning: Trying to access array offset on null for the next level. array_key_exists checks one level, so when null values matter you walk the path yourself.
<?php
$order = [
'id' => 7,
'customer' => ['name' => 'Ada', 'address' => ['city' => 'London']],
'notes' => null,
];
// isset and ?? never warn, however many levels are missing
var_dump(isset($order['customer']['address']['city']));
var_dump(isset($order['customer']['phone']['mobile']));
var_dump(isset($order['shipping']['address']['city']));
echo $order['shipping']['address']['city'] ?? 'no city', "\n";
echo $order['notes']['text'] ?? 'no notes', "\n";
// array_key_exists checks one level, so test each level in turn
function hasPath(array $data, string ...$keys): bool
{
$current = $data;
foreach ($keys as $key) {
if (!is_array($current) || !array_key_exists($key, $current)) {
return false;
}
$current = $current[$key];
}
return true;
}
var_dump(hasPath($order, 'customer', 'address', 'city'));
var_dump(hasPath($order, 'notes'));
var_dump(hasPath($order, 'notes', 'text'));
Output
isset is bool(true) only for the full path to city; the missing phone and shipping levels give bool(false) with nothing on the error output. ?? also steps through notes, which is null, and prints no notes. hasPath reports that notes exists even though it is null (bool(true)), which isset can't tell you, and returns bool(false) for notes then text because null is not an array.
5Integer and string keys: "1" and 1 are the same key
PHP arrays only have two kinds of keys, int and string, and a string that is a plain decimal integer is turned into an int when it is used as a key. So a lookup with "1" from a URL or form finds the key 1 you stored, and the other way round. Only the canonical form is converted: "01", "1.0" and " 1" stay strings. The same rule means array_keys can hand back integers you stored as strings.
<?php $items = [1 => 'one', 2 => 'two']; // "1" is cast to 1 when used as a key, so both lookups find it var_dump(isset($items['1'])); var_dump(array_key_exists('2', $items)); // A key stored as "3" comes back as the integer 3 $items['3'] = 'three'; var_dump(array_keys($items)); // Only canonical integer strings are cast $codes = ['01' => 'leading zero', '1.0' => 'decimal', ' 1' => 'space']; var_dump(array_key_exists(1, $codes)); var_dump(array_key_exists('01', $codes)); // true is stored as the key 1 $flags = [true => 'yes']; var_dump(isset($flags[1]));
Output
Both string lookups return bool(true), and array_keys lists int(3), not string(1) "3", so a strict comparison such as $key === '3' on those keys fails. In $codes none of the three keys becomes 1, so array_key_exists(1, $codes) is bool(false). Two more conversions print deprecation messages on the PHP 8.5 that runs these examples: a float key is truncated with Deprecated: Implicit conversion from float 1.5 to int loses precision, and a null key becomes '' with Deprecated: Using null as an array offset is deprecated, use an empty string instead.
6Checking for a value, not a key
In a list such as ['admin', 'editor'] the keys are 0, 1 and so on, so array_key_exists('admin', $roles) is the wrong question. To ask whether a value is in the array use in_array, and to find the key that holds it use array_search. Pass true as the third argument to compare with ===: the default loose comparison treats numeric strings as numbers. Both scan the whole array, so for many lookups flip the array once and use isset on the result.
<?php $roles = ['admin', 'editor', 'viewer']; // in_array looks at values; the keys here are 0, 1, 2 var_dump(in_array('editor', $roles, true)); var_dump(array_key_exists('editor', $roles)); // array_search returns the key or false, and 0 is a valid key $key = array_search('admin', $roles, true); if ($key !== false) { echo "admin is at key $key\n"; } // Loose comparison treats numeric strings as numbers $ids = ['10', '20', 'abc']; var_dump(in_array('1e1', $ids)); var_dump(in_array('1e1', $ids, true)); // Many lookups: flip once, then isset is a hash lookup $allowed = array_flip($roles); var_dump(isset($allowed['viewer']), isset($allowed['owner']));
Output
in_array finds 'editor', while array_key_exists on the same list says bool(false). array_search returns 0 for 'admin', which is falsy, so test it with !== false as shown, never with a plain if. Without the strict flag, '1e1' matches '10' because both are numeric strings worth 10; with true it doesn't. array_flip turns the values into keys, so each later check is an isset instead of a scan.
7Which should you use?
| Method | Key with a null value | Missing key | Best for |
|---|---|---|---|
| isset($a['k']) | false | false, no warning | Most checks; also nested paths |
| array_key_exists('k', $a) | true | false, no warning | When null is a real value |
| $a['k'] ?? $default | default | default, no warning | Reading a value with a fallback |
| $a['k'] ??= $default | replaced | added | Filling in missing settings |
| $a['k'] | null | null plus a warning | Keys that must always be there |
| in_array($v, $a, true) | n/a (checks values) | n/a (checks values) | Is a value in a list? |
Frequently asked questions
Why do I get "Warning: Undefined array key" or "Notice: Undefined index"?
Your code reads $array['key'] for a key the array does not have. PHP 8 prints Warning: Undefined array key "key", PHP 7 printed Notice: Undefined index: key (or Undefined offset for an integer key), and both return null and carry on. Check the key first with isset or array_key_exists, or read it with $array['key'] ?? $default. On a form or URL parameter, $_GET['page'] ?? 1 is the usual fix.
What is the difference between isset() and array_key_exists()?
Only a null value tells them apart. array_key_exists('k', $a) returns true whenever the key is in the array, while isset($a['k']) returns false if the value is null. isset is shorter, accepts several keys at once and is safe on nested keys; array_key_exists is the one to use when null is a meaningful value.
Is isset() faster than array_key_exists()?
Not on current PHP. Since PHP 7.4, a plain array_key_exists() call outside a namespace (or written as \array_key_exists()) compiles to its own opcode instead of a function call, and a run here timed 5 million calls of each at about 73 ms. The old advice that isset is much faster dates from PHP 5. Pick by meaning: if a null value must count as present, you need array_key_exists.
How do I check if a key exists in an object?
Use property_exists($obj, 'name') to ask whether the class or object has the property, even if it is null, private or not yet initialized, and isset($obj->name) to ask whether it is accessible and not null. In PHP 8, array_key_exists on an object throws TypeError: array_key_exists(): Argument #2 ($array) must be of type array, stdClass given. For your own class that implements ArrayAccess, isset($obj['k']) calls its offsetExists method.
Is empty() a safe way to check a key?
It is safe in that empty($a['k']) never warns, but it asks a different question: it returns true for a missing key, null, false, 0, '0', '' and an empty array. Use it when all of those mean "nothing here"; to tell a missing key from a 0 or an empty string, use isset or array_key_exists.
How do I check that several keys exist at once?
For keys that must be set and not null, isset($a['id'], $a['name']) takes them all and returns true only if every one is set. To list which keys are missing, compare against the required keys: array_keys(array_diff_key(array_flip($required), $row)) returns the missing ones, for example ['email', 'phone'].