array_key_exists
(PHP 4 >= 4.0.7, PHP 5, PHP 7, PHP 8)
array_key_exists — 检查数组里是否有指定的键名或索引
说明
数组里有键 key
时,array_key_exists() 返回 true
。
key
可以是任何能作为数组索引的值。
参数
key
-
要检查的键。
array
-
一个数组,包含待检查的键。
更新日志
版本 | 说明 |
---|---|
8.0.0 |
key 参数现在接受
bool 、float 、int 、null 、resource
和 string 作为参数。
|
示例
示例 #1 array_key_exists() 示例
<?php
$search_array = array('first' => 1, 'second' => 4);
if (array_key_exists('first', $search_array)) {
echo "The 'first' element is in the array";
}
?>
注释
注意:
由于为了兼容以前版本,如果 object 当做
array
传入 array_key_exists(),同时key
是对象的属性,也会返回true
。 此行为在 PHP 7.4.0 弃用且在 PHP 8.0.0 移除。要检查对象是否有某个属性,应该使用 property_exists()。
参见
- isset() - 检测变量是否已声明并且其值不为 null
- array_keys() - 返回数组中部分的或所有的键名
- in_array() - 检查数组中是否存在某个值
- property_exists() - 检查对象或类是否具有该属性
+添加备注
用户贡献的备注 2 notes
Rumour ¶
1 year ago
In PHP7+ to find if a value is set in a multidimensional array with a fixed number of dimensions, simply use the Null Coalescing Operator: ??
So for a three dimensional array where you are not sure about any of the keys actually existing
<?php
// instead of:
$exists = array_key_exists($key1, $arr) && array_key_exists($key2, $arr[$key1]) && array_key_exists($key3, $arr[$key1][$key2]) ;
// use:
$exists = array_key_exists($key3, $arr[$key1][$key2]??[]) ;
?>
Julian ¶
1 year ago
When you want to check multiple array keys:
<?php
$array = [];
$array['a'] = '';
$array['b'] = '';
$array['c'] = '';
$array['d'] = '';
$array['e'] = '';
// all given keys a,b,c exists in the supplied array
var_dump(array_keys_exists(['a','b','c'], $array)); // bool(true)
function array_keys_exists(array $keys, array $array): bool
{
$diff = array_diff_key(array_flip($keys), $array);
return count($diff) === 0;
}
备份地址:http://www.lvesu.com/blog/php/function.array-key-exists.php