ZetCode

PHP key_exists 函数

最后修改于 2025 年 3 月 13 日

PHP key_exists 函数用于检查指定的键是否存在于数组中。它是 PHP 中进行数组键验证的重要工具。

基本定义

key_exists 函数检查给定键是否存在于数组中。如果键存在,则返回 true;否则返回 false。

语法:key_exists(string|int $key, array $array): bool。该函数同时支持字符串键和整数键。它是 array_key_exists 的别名。

基本的 key_exists 示例

演示如何在简单的关联数组中检查键。

basic_key_exists.php
<?php

$user = [
    'name' => 'John',
    'age' => 30,
    'email' => 'john@example.com'
];

if (key_exists('email', $user)) {
    echo "Email exists: " . $user['email'];
} else {
    echo "Email does not exist";
}

此代码检查 'email' 键是否存在于 $user 数组中。由于存在,代码会输出电子邮件地址。在此情况下,函数返回 true。

检查数字键

key_exists 同时支持字符串键和数字数组键。

numeric_keys.php
<?php

$colors = [1 => 'red', 2 => 'green', 3 => 'blue'];

if (key_exists(2, $colors)) {
    echo "Key 2 exists with value: " . $colors[2];
} else {
    echo "Key 2 does not exist";
}

此代码验证数字键 2 是否存在于 $colors 数组中。函数正确识别了该键并返回其值 'green'。

检查不存在的键

在检查不存在的键时,函数返回 false。

nonexistent_key.php
<?php

$settings = [
    'theme' => 'dark',
    'notifications' => true
];

$key = 'language';
$exists = key_exists($key, $settings);

echo $exists ? "Key '$key' exists" : "Key '$key' does not exist";

此代码检查数组中不存在的 'language' 键。函数返回 false,并且代码输出该键不存在。

Null 值处理

即使键的值为 null,key_exists 也会返回 true。

null_values.php
<?php

$data = [
    'username' => 'johndoe',
    'middle_name' => null,
    'last_name' => 'Doe'
];

$key = 'middle_name';
if (key_exists($key, $data)) {
    echo "Key '$key' exists (value is null)";
} else {
    echo "Key '$key' does not exist";
}

这表明 key_exists 只检查键是否存在,而不检查值的内容。尽管 'middle_name' 的值为 null,它仍然返回 true。

key_exists 和 isset 的区别

演示 key_existsisset 的区别。

key_exists_vs_isset.php
<?php

$array = [
    'a' => 1,
    'b' => null,
    'c' => 0
];

echo "key_exists('b', \$array): " . (key_exists('b', $array) ? 'true' : 'false') . "\n";
echo "isset(\$array['b']): " . (isset($array['b']) ? 'true' : 'false') . "\n";

对于键 'b'(值为 null),key_exists 返回 true,而 isset 返回 false。isset 还会检查值是否不为 null。

最佳实践

来源

PHP key_exists 文档

本教程通过实际示例介绍了 PHP key_exists 函数,展示了其在数组键验证场景中的用法。

作者

我叫 Jan Bodnar,是一位充满热情的程序员,拥有丰富的编程经验。我自 2007 年起撰写编程文章。至今,我已撰写了超过 1400 篇文章和 8 本电子书。我在编程教学方面拥有十多年的经验。

列出 所有 PHP 数组函数