How to check if an array has an element at the specified index?
php
Solution
You can use either the language construct `isset`, or the function `array_key_exists` : numeric or string key doesn't matter : it's still an associative array, for PHP.
`isset` should be a bit faster (as it's not a function), but will return `false` if the element exists and has the value `NULL`.
For example, considering this array :
$a = array(
123 => 'glop',
456 => null,
);
And those three tests, relying on `isset` :
var_dump(isset($a[123]));
var_dump(isset($a[456]));
var_dump(isset($a[789]));
You'll get this kind of output :
boolean true
boolean false
boolean false
Because :
- in the first case, the element exists, and is not `null`
- in the second, the element exists, but is `null`
- and, in the third, the element doesn't exist
On the other hand, using `array_key_exists` like in this portion of code :
var_dump(array_key_exists(123, $a));
var_dump(array_key_exists(456, $a));
var_dump(array_key_exists(789, $a));
You'll get this output :
boolean true
boolean true
boolean false
Because :
- in the two first cases, the element exists -- even if it's `null` in the second case
- and, in the third, it doesn't exist.
Problem
I know there is array_key_exists() but after reading the documentation I'm not really sure if it fits for this case: I have an $array and an $index. Now I want to access the $array, but don't know if it has an index matching $index. I'm not talking about an associative array, but an plain boring normal numerically indexed array. Is there an safe way to figure out if I would really access an $array element with the given $index (which is an integer!)? PHP may not care if I access an array with an index out of bounds and maybe just returns NULL or so, but I don't want to even attempt to code dirty, so I want to check if the array has the key, or not ;-)