Check if key exists

Download php eBook

Example

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

Note that isset() treats a null valued element as non-existent. Whereas !empty() does the same for any element that equals false (using a weak comparision; for example, null, '' and 0 are all treated as false by !empty()). While isset($map['foobar']); is true, !empty($map['foobar']) is false. This can lead to mistakes (for example, it is easy to forget that the string '0' is treated as false) so use of !empty() is often frowned upon.

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().

Stats

Contributors: 11
2017-03-06
Licensed under: CC-BY-SA

Not affiliated with Stack Overflow
Rip Tutorial: info@zzzprojects.com

Download eBook