What's the difference between isset() and array_key_exists()? [duplicate]

How do the following two function calls compare:

isset($a['key'])

array_key_exists('key', $a)

Solution 1:

array_key_exists will definitely tell you if a key exists in an array, whereas isset will only return true if the key/variable exists and is not null.

$a = array('key1' => 'フーバー', 'key2' => null);

isset($a['key1']);             // true
array_key_exists('key1', $a);  // true

isset($a['key2']);             // false
array_key_exists('key2', $a);  // true

There is another important difference: isset doesn't complain when $a does not exist, while array_key_exists does.

Solution 2:

Between array_key_exists and isset, though both are very fast [O(1)], isset is significantly faster. If this check is happening many thousands of times, you'd want to use isset.

It should be noted that they are not identical, though -- when the array key exists but the value is null, isset will return false and array_key_exists will return true. If the value may be null, you need to use array_key_exists.


As noted in comments, if your value may be null, the fast choice is:

isset($foo[$key]) || array_key_exists($key, $foo)

Solution 3:

The main difference when working on arrays is that array_key_exists returns true when the value is null, while isset will return false when the array value is set to null.

See isset on the PHP documentation site.