php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #71239 Language construct for array_key_exists() (performance)
Submitted: 2015-12-29 17:24 UTC Modified: 2020-01-29 15:57 UTC
Votes:3
Avg. Score:5.0 ± 0.0
Reproduced:2 of 2 (100.0%)
Same Version:0 (0.0%)
Same OS:0 (0.0%)
From: andreas at dqxtech dot net Assigned: nikic (profile)
Status: Closed Package: Arrays related
PHP Version: 7.0.2RC1 OS:
Private report: No CVE-ID: None
Welcome back! If you're the original bug submitter, here's where you can edit the bug or add additional notes.
If you forgot your password, you can retrieve your password here.
Password:
Status:
Package:
Bug Type:
Summary:
From: andreas at dqxtech dot net
New email:
PHP Version: OS:

 

 [2015-12-29 17:24 UTC] andreas at dqxtech dot net
Description:
------------
There are places on the web telling me that array_key_exists($k, $a) is slower than isset($a[$k]). https://startpage.com/do/search?query=php+performance+isset+vs+array_key_exists&cat=web&pl=chrome&language=english

Tests with PHP 5.5.9 confirm this, it seems that array_key_exists() uses almost 4x the time of isset().

On the other hand: Semantically, array_key_exists() is preferable over isset().
If you already know that $a is an array and not null, and that $k is a valid array key, then you don't want to have this tested again. You want TRUE or FALSE if the variables are set, and a warning (and FALSE, I guess) otherwise.

This allows the IDE to warn you if you test a variable that is possibly undefined, or possibly not an array. With isset(), the IDE will keep silent, which can lead to hidden bugs.

In theory, array_key_exists() should be faster than isset(), because there are fewer cases to consider.. but it is not, because one is a function and the other a "language construct".

Aside of that, there is of course the difference of how NULL values are handled.. In fact, in an ideal world, there would be two versions of array_key_exists(). Both with the performance of a language construct. But with a different behavior for NULL values.


Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2018-08-23 00:49 UTC] carusogabriel@php.net
Related to Bug #71239
 [2018-08-23 00:50 UTC] carusogabriel@php.net
Related to Bug #76148
 [2020-01-29 15:57 UTC] nikic@php.net
-Status: Open +Status: Closed -Assigned To: +Assigned To: nikic
 [2020-01-29 15:57 UTC] nikic@php.net
array_key_exists() has an optimized opcode implementation since PHP 7.4.
 
PHP Copyright © 2001-2025 The PHP Group
All rights reserved.
Last updated: Thu Jan 02 23:01:30 2025 UTC