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

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

Feedback about page:

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


Arrays:
* Arrays
* Check if key exists

Table Of Contents
2 Arrays
4 Types
10 Cookies
14 JSON
15 SOAP
17 cURL
19 XML
21 Traits
35 UTF-8
36 URLs
38 PHPDoc
41 Loops
44 Closur
72 YAML
77 Cache
78 Streams
81 PDO
82 SQLite3
83 Sockets
87 MongoDB
93 IMAP
94 Redis
95 Imagick
102 APCu
108 PSR