Search code examples
phparraysissetarray-key-exists

Is (isset(..) || array_key_exists(...)) a faster way of detecting null values than just array_key_exists(...))?


While researching how to detect null values in an array, I came across some user's comment under the http://www.php.net/manual/en/function.array-key-exists.php manual page.

It said that

if (isset(..) || array_key_exists(...))
{
...
}

is faster than doing

if array_key_exists(...))
{
...
}

The bench marks posted for 100000 runs were

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

My question:

Is (isset(..) || array_key_exists(...)) faster than array_key_exists() ? If so, why?

EDIT: In writing out this question I think I found my answer. I've decided to post the question anyway to see if my thinking is correct.


Solution

  • Which is faster depends on the array you are checking. If the array contains a value other than null, "", or 0

    if (isset(..) || array_key_exists(...)){    
    }
    

    the above code will be faster, because isset will be checked then the code executed. Array_key_exists will not be run.

    If the array contains a value of null, "", or 0 then isset will be tested and then array_key_exists. This will take longer than simply testing for array_key_exists by itself.

    So the question which is faster depends a lot on the array you are checking.

    A lot of people have said that it doesn't really matter. They didn't explain why it doesn't matter though. I guess they mean that the speed improvements are so minimal that it isn't worth bothering with. They may also mean that which is faster is dependent on the values assigned in your array (and thus different each time.)

    Ultimately though, if you know that most of the keys will be assigned values other than null, "" or 0 and you really need to determine when null values are assigned, then use

    if (isset(..) || array_key_exists(...)){    
    }