array_key_exists() versus isset()
Everyone here has the good habit of testing for the existence of keys in a hash before accessing them, since otherwise logs can quickly fill up with notices. There are two ways to make this check:
1. array_key_exists()
2. isset()
You should prefer to use isset(), as it is significantly faster. Here is a test and the results I got on my computer:
-
for ($i = 0; $i < 1000000; $i++) {
-
echo "Not here\n";
-
}
-
}
This took 20.5 seconds to run.
-
for ($i = 0; $i < 1000000; $i++) {
-
echo "Not here\n";
-
}
-
}
This only took 0.4.
isset() is faster because it is a language construct; it does not suffer the overhead of a function call like array_key_exists() does. However, the two are not completely interchangeable. isset() also checks the value associated with the key, and will return false if that value is null. On the other hand, array_key_exists() only checks the key, and will return true for keys that point to a null value. Sometimes this distinction is important.
-
-
// This is true.
-
-
// But this is false.
When you don’t need to distinguish the null value, please use isset().
Also note that there is a common idiom for avoiding either of these. By prefixing an expression with ‘@’, PHP ignores any errors for it. A lot of people use this for brevity, as they avoid using either two operations above. They would write
-
if (@$foo[‘not_here’] === ‘nomnom’) {
-
…
-
}
In the cases where the key is not actually there, using ‘@’ is going to be slower than isset() because of the I/O involved in logging the notice generated by the missing key. But even with that I/O, using ‘@’ is still an order of magnitude faster than array_key_exists(). So please avoid array_key_exists() unless you specifically need to know when the key exists and may have a null value.
Related posts:
- PHP Puts the Un in Unset
- Messing With Namespaces and Anonymous Functions
- Pitfalls With Optional Arguments
- More PHP Woes
- Easy Documentation for Git, MySQL, PHP, et cetera


Leave a comment