Answer to an old question as no answer here seem to address the 'warning' problem (explanation follows)
Basically, in this case of checking if a key exists in an array, isset
- tells if the expression (array) is defined, and the key is set
- no warning or error if the var is not defined, not an array ...
- but returns false if the value for that key is null
and array_key_exists
- tells if a key exists in an array as the name implies
- but gives a warning if the array parameter is not an array
So how do we check if a key exists which value may be null in a variable
- that may or may not be an array
- (or similarly is a multidimensional array for which the key check happens at dim 2 and dim 1 value may not be an array for the 1st dim (etc...))
without getting a warning, without missing the existing key when its value is null (what were the PHP devs thinking would also be an interesting question, but certainly not relevant on SO). And of course we don't want to use @
isset($var[$key]); // silent but misses null values
array_key_exists($key, $var); // works but warning if $var not defined/array
It seems is_array
should be involved in the equation, but it gives a warning if $var
is not defined, so that could be a solution:
if (isset($var[$key]) ||
isset($var) && is_array($var) && array_key_exists($key, $var)) ...
which is likely to be faster if the tests are mainly on non-null values. Otherwise for an array with mostly null values
if (isset($var) && is_array($var) && array_key_exists($key, $var)) ...
will do the work.