I wanted to add my 2 cents on this question, since I was missing a middle way out.
As already told isset()
will evaluate the value of the key so it will return false
if that value is null
where array_key_exists()
will only check if the key exists in the array.
I've ran a simple benchmark using PHP 7, the results shown is the time it took to finish the iteration:
$a = [null, true];
isset($a[0]) # 0.3258841 - false
isset($a[1]) # 0.28261614 - true
isset($a[2]) # 0.26198816 - false
array_key_exists(0, $a) # 0.46202087 - true
array_key_exists(1, $a) # 0.43063688 - true
array_key_exists(2, $a) # 0.37593913 - false
isset($a[0]) || array_key_exists(0, $a) # 0.66342998 - true
isset($a[1]) || array_key_exists(1, $a) # 0.28389215 - true
isset($a[2]) || array_key_exists(2, $a) # 0.55677581 - false
array_key_isset(0, $a) # 1.17933798 - true
array_key_isset(1, $a) # 0.70253706 - true
array_key_isset(2, $a) # 1.01110005 - false
I've added the results from this custom function with this benchmark as well for completion:
function array_key_isset($k, $a){
return isset($a[$k]) || array_key_exists($k, $a);
}
As seen and already told isset()
is fastest method but it can return false if the value is null
. This could give unwanted results and usually one should use array_key_exists()
if that's the case.
However there is a middle way out and that is using isset() || array_key_exists()
. This code is generally using the faster function isset()
and if isset()
returns false only then use array_key_exists()
to validate. Shown in the table above, its just as fast as plainly calling isset()
.
Yes, it's a bit more to write and wrapping it in a function is slower but a lot easier. If you need this for performance, checking big data, etc write it out full, otherwise if its a 1 time usage that very minor overhead in function array_key_isset()
is negligible.
isset
will never behave exactly likearray_key_exists
, the code example that supposedly makes it behave identically throws a Notice if the key doesn't exist. – deceze♦in_array
? maettig.com/1397246220 – DanManin_array
isO(n)
because it checks the values not the keys. They are almost always going to be slower unless yourn
is extremely small. – Pacerier$array[$key] === null
? – Pacerier