Check if key exists

suggest change

Use array_key_exists() or isset() or !empty():

$map = [
    'foo' => 1,
    'bar' => null,
    'foobar' => '',
];

array_key_exists('foo', $map); // true
isset($map['foo']); // true
!empty($map['foo']); // true

array_key_exists('bar', $map); // true
isset($map['bar']); // false
!empty($map['bar']); // false

isset() treats a null value as unset. empty() uses boolean conversion, not ==. null, '', 0, '0', and false are empty, so isset($map['foobar']) is true while !empty($map['foobar']) is false. '00' is not empty, even though '00' == false. Forgetting that '0' is empty is a common mistake, so !empty() is often a poor existence check.

Note also that isset() and !empty() will work (and return false) if $map is not defined at all. This makes them somewhat error-prone to use:

// Note "long" vs "lang", a tiny typo in the variable name.
$my_array_with_a_long_name = ['foo' => true];
array_key_exists('foo', $my_array_with_a_lang_name); // shows a warning
isset($my_array_with_a_lang_name['foo']); // returns false

You can also check for ordinal arrays:

$ord = ['a', 'b']; // equivalent to [0 => 'a', 1 => 'b']

array_key_exists(0, $ord); // true
array_key_exists(2, $ord); // false

Note that isset() has better performance than array_key_exists() as the latter is a function and the former a language construct.

You can also use key_exists(), which is an alias for array_key_exists().

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents