检查密钥是否存在
使用 array_key_exists() 或 isset() 或 !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() 将 null 值元素视为不存在。而 !empty() 对于任何等于 false 的元素都是一样的(使用弱比较;例如,null,''和 0 都被 !empty() 视为假)。虽然 isset($map['foobar']); 是 true,但 !empty($map['foobar']) 是 false。这可能会导致错误(例如,很容易忘记字符串'0'被视为假)因此使用 !empty() 通常是不受欢迎的。
另请注意,如果根本没有定义 $map,isset() 和 !empty() 将起作用(并返回 false)。这使得它们在某种程度上容易出错:
// 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
你还可以检查序数数组:
$ord = ['a', 'b']; // equivalent to [0 => 'a', 1 => 'b']
array_key_exists(0, $ord); // true
array_key_exists(2, $ord); // false
请注意,isset() 具有比 array_key_exists() 更好的性能,因为后者是一种功能而前者是一种语言结构。
你也可以使用 key_exists() ,这是 array_key_exists() 的别名。