search

Home  >  Q&A  >  body text

What is a faster and more efficient way to check if a key exists in a PHP array?

Consider these two examples...

$key = 'jim';

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

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

I'm interested to know if these two are better. I've been using the first example, but I've seen a lot of people on this site using the second example.

So, which one is better? hurry up? Clearer intention?

P粉512363233P粉512363233424 days ago559

reply all(2)I'll reply

  • P粉969666670

    P粉9696666702023-10-17 00:59:09

    If you are interested in some of the tests I recently completed:

    https://stackoverflow.com/a/21759158/520857

    Summary:

    | Method Name                              | Run time             | Difference
    =========================================================================================
    | NonExistant::noCheckingTest()            | 0.86004090309143     | +18491.315775911%
    | NonExistant::emptyTest()                 | 0.0046701431274414   | +0.95346080503016%
    | NonExistant::isnullTest()                | 0.88424181938171     | +19014.461681183%
    | NonExistant::issetTest()                 | 0.0046260356903076   | Fastest
    | NonExistant::arrayKeyExistsTest()        | 1.9001779556274      | +209.73055713%

    reply
    0
  • P粉713866425

    P粉7138664252023-10-17 00:41:48

    isset() is faster, but not the same as array_key_exists().

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

    Given If the key exists and the value is NULL, isset() will return false.

    reply
    0
  • Cancelreply