Search code examples
phpperformance

What's quicker and better to determine if an array key exists in PHP?


Consider these 2 examples...

$key = 'jim';

// example 1
if (isset($array[$key])) {
    // ...
}

// example 2    
if (array_key_exists($key, $array)) {
    // ...
}

I'm interested in knowing if either of these are better. I've always used the first, but have seen a lot of people use the second example on this site.

So, which is better? Faster? Clearer intent?


Solution

  • isset() is faster, but it's not the same as array_key_exists().

    array_key_exists() purely checks if the key exists, even if the value is NULL.

    Whereas isset() will return false if the key exists and value is NULL.