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 😉
You can use either the language construct
isset, or the functionarray_key_exists: numeric or string key doesn’t matter : it’s still an associative array, for PHP.issetshould be a bit faster (as it’s not a function), but will returnfalseif the element exists and has the valueNULL.For example, considering this array :
And those three tests, relying on
isset:You’ll get this kind of output :
Because :
nullnullOn the other hand, using
array_key_existslike in this portion of code :You’ll get this output :
Because :
nullin the second case