How to check if an array element exists?



Example: I'm checking for the existence of an array element like this:

if (!self::$instances[$instanceKey]) {
    $instances[$instanceKey] = $theInstance;

However, I keep getting this error:

Notice: Undefined index: test in /Applications/MAMP/htdocs/mysite/MyClass.php on line 16

Of course, the first time I want an instance, $instances will not know the key. I guess my check for available instance is wrong?

12/27/2009 3:12:46 PM

Accepted Answer

You can use either the language construct isset, or the function array_key_exists.

isset should be a bit faster (as it's not a function), but will return false if the element exists and has the value NULL.

For example, considering this array :

$a = array(
    123 => 'glop', 
    456 => null, 

And those three tests, relying on isset :


The first one will get you (the element exists, and is not null) :

boolean true

While the second one will get you (the element exists, but is null) :

boolean false

And the last one will get you (the element doesn't exist) :

boolean false

On the other hand, using array_key_exists like this :

var_dump(array_key_exists(123, $a));
var_dump(array_key_exists(456, $a));
var_dump(array_key_exists(789, $a));

You'd get those outputs :

boolean true
boolean true
boolean false

Because, in the two first cases, the element exists -- even if it's null in the second case. And, of course, in the third case, it doesn't exist.

For situations such as yours, I generally use isset, considering I'm never in the second case... But choosing which one to use is now up to you ;-)

For instance, your code could become something like this :

if (!isset(self::$instances[$instanceKey])) {
    $instances[$instanceKey] = $theInstance;
12/27/2009 3:24:28 PM

array_key_exists() is SLOW compared to isset(). A combination of these two (see below code) would help.

It takes the performance advantage of isset() while maintaining the correct checking result (i.e. return TRUE even when the array element is NULL)

if (isset($a['element']) || array_key_exists('element', $a)) {
       //the element exists in the array. write your code here.

The benchmarking comparison: (extracted from below blog posts).

array_key_exists() only : 205 ms
isset() only : 35ms
isset() || array_key_exists() : 48ms

See and

for detailed discussion.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow