20 November 2006
Comparing array_key_exists With isset
There are two functions for determining the existence of elements in an array: isset and array_key_exists. They are very similar in use, but there are subtle differences.
The biggest difference is speed. array_key_exists takes about 33% longer to execute than isset. For just a few checks, it’s a negligible difference. But in a loop, it will take a while longer. Looped over 100,000 times, isset takes 0.2s less on my dual G4 800 MHz PowerMac.
The next is flexibility. isset operates on values, and why not? It also checks if variables are defined. Therefore, values which resolve to NULL return FALSE with isset but TRUE with array_key_exists. So if your array contains NULL, you must incur the performance penalty of array_key_exists.
isset works by default with real variables. array_key_exists would need to be supplied the current scope state with a call to check if a variable exists, and that would likely entail a call to get_defined_vars. So for the existance of variables, isset is better.
The fourth difference is purely style. isset is very PHP specific. You’ll find functions like array_key_exists in other languages, so for readability I would encourage use of array_key_exists. array_key_exists also seems more consistent even within PHP. Most functions will cause errors at error level E_NOTICE if you try to access a non-existent array index. isset does not.
Those are the differences. The two do almost identical things, but there are differences in what each does best and as a PHP developer, you need to know which to use when. I find that I always use array_key_exists for arrays and isset for scalars. I incur a runtime cost of a fraction of a second to do that, but to me, the clarity and added reliability are worth it. But your exact circumstances will determine which is best for you. If you control the data that is being examined and know there are no NULL values, you can use isset and save time. If you can’t guarantee that, array_key_exists is the only way to guarantee accurate results. Through the use of some special functions you can mutate a call to one into a call to the other.
There is no steadfast rule. You need to learn the subtleties of each and use the correct one for your needs at the time.

