How to Check Array Keys in PHP with array_key_exists and isset
This guide explains PHP's array_key_exists function, shows how to use it with code examples, compares it to isset, and highlights the key difference when array values are null, helping developers reliably verify key existence in associative arrays.
PHP provides the built-in array_key_exists() function to determine whether a specific key name is present in an array. The function accepts two parameters—the key to check and the array to inspect—and returns true if the key exists, otherwise false.
Usage Example:
<?php
// Create an associative array
$student = array(
"name" => "张三",
"age" => 20,
"gender" => "男"
);
// Check if the key "name" exists
if (array_key_exists("name", $student)) {
echo "学生姓名存在于数组中";
} else {
echo "学生姓名不存在于数组中";
}
// Check if the key "grade" exists
if (array_key_exists("grade", $student)) {
echo "学生成绩存在于数组中";
} else {
echo "学生成绩不存在于数组中";
}
?>Running the script outputs:
学生姓名存在于数组中
学生成绩不存在于数组中The result shows that the key name is present in $student, while the key grade is not.
Besides array_key_exists(), the isset() function can also test for key existence. The main difference appears when the key's value is null: array_key_exists() returns true, whereas isset() returns false.
Comparison of isset() and array_key_exists():
<?php
// Create an associative array with a null value
$student = array(
"name" => "张三",
"age" => null,
"gender" => "男"
);
// Using isset()
if (isset($student["name"])) {
echo "学生姓名存在于数组中";
} else {
echo "学生姓名不存在于数组中";
}
if (isset($student["age"])) {
echo "学生年龄存在于数组中";
} else {
echo "学生年龄不存在于数组中";
}
// Using array_key_exists()
if (array_key_exists("name", $student)) {
echo "学生姓名存在于数组中";
} else {
echo "学生姓名不存在于数组中";
}
if (array_key_exists("age", $student)) {
echo "学生年龄存在于数组中";
} else {
echo "学生年龄不存在于数组中";
}
?>Output of the above code:
学生姓名存在于数组中
学生年龄不存在于数组中
学生姓名存在于数组中
学生年龄存在于数组中The output demonstrates that isset() treats a null value as non‑existent (returning false), while array_key_exists() treats the same null value as a valid key (returning true).
Overall, array_key_exists() is a reliable tool for checking key presence in PHP arrays, especially when distinguishing between missing keys and keys that hold null values.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
php Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
