PHP 8.3.27 Released!

array_key_exists

(PHP 4 >= 4.0.7, PHP 5, PHP 7, PHP 8)

array_key_exists检查数组里是否有指定的键名或索引

说明

array_key_exists(string|int|float|bool|resource|null $key, array $array): bool

数组里有键 key 时,array_key_exists() 返回 truekey 可以是任何能作为数组索引的值。

参数

key

要检查的键。

array

一个数组,包含待检查的键。

返回值

成功时返回 true, 或者在失败时返回 false

注意:

array_key_exists() 仅仅搜索第一维的键。 多维数组里嵌套的键不会被搜索到。

更新日志

版本 说明
8.0.0 key 参数现在接受 boolfloatintnullresourcestring 作为参数。
8.0.0 不再支持将 object 传递给 array 参数。
7.4.0 已弃用将 object 传递给 array 参数。建议使用 property_exists()

示例

示例 #1 array_key_exists() 示例

<?php
$searchArray
= ['first' => 1, 'second' => 4];
var_dump(array_key_exists('first', $searchArray));
?>

以上示例会输出:

bool(true)

示例 #2 array_key_exists()isset() 的对比

isset() 对于数组中为 null 的值不会返回 true,而 array_key_exists() 会。

<?php
$searchArray
= ['first' => null, 'second' => 4];

var_dump(isset($searchArray['first']));
var_dump(array_key_exists('first', $searchArray));
?>

以上示例会输出:

bool(false)
bool(true)

参见

  • isset() - 检测变量是否已声明并且其值不为 null
  • array_keys() - 返回数组中部分的或所有的键名
  • in_array() - 检查数组中是否存在某个值
  • property_exists() - 检查对象或类是否具有该属性

添加备注

用户贡献的备注 3 notes

up
11
Rumour
2 years 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]??[]) ;

?>
up
12
Julian
2 years 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;
}
up
-1
developerxyz852 at gmail dot com
7 months ago
<?php

// Define an associative array
$userProfile = [
'name' => 'John Doe',
'email' => 'john.doe@example.com',
'age' => 30,
'country' => 'USA'
];

// Key to check
$keyToCheck = 'email';

// Use array_key_exists to check if the key exists in the array
if (array_key_exists($keyToCheck, $userProfile)) {
echo
"The key '$keyToCheck' exists in the array with value: " . $userProfile[$keyToCheck];
} else {
echo
"The key '$keyToCheck' does not exist in the array.";
}

?>
To Top