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:

  1. for ($i = 0; $i < 1000000; $i++) {
  2.         if (array_key_exists(‘not_here’, $foo) && $foo[‘not_here’] === ‘nomnom’) {
  3.                 echo "Not here\n";
  4.         }
  5. }

This took 20.5 seconds to run.

  1. for ($i = 0; $i < 1000000; $i++) {
  2.         if (isset($foo[‘not_here’]) && $foo[‘not_here’] === ‘nomnom’) {
  3.                 echo "Not here\n";
  4.         }
  5. }

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.

  1. $foo = array(‘bar’ => null);
  2.  
  3. // This is true.
  4. array_key_exists(‘bar’, $foo);
  5.  
  6. // But this is false.
  7. isset($foo[‘bar’]);

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

  1. if (@$foo[‘not_here’] === ‘nomnom’) {
  2.         …
  3.     }

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:

  1. PHP Puts the Un in Unset
  2. Messing With Namespaces and Anonymous Functions
  3. Pitfalls With Optional Arguments
  4. More PHP Woes
  5. Easy Documentation for Git, MySQL, PHP, et cetera
0 Comment   |   Posted in PHP,Programming Languages,Tips & Tricks,blog by EricR on June 01, 2010