在 PHP 中,你可以使用 array_key_exists() 函数来判断数组中是否存在某个键(key)。此外,你还可以使用 isset() 函数来检查键是否存在且其值不为 null。以下是两种方法的示例:
使用 array_key_exists()
$array = [
'name' => 'Alice',
'age' => 30,
'city' => 'New York'
];
$keyToCheck = 'age';
if (array_key_exists($keyToCheck, $array)) {
echo "Key '$keyToCheck' exists in the array.";
} else {
echo "Key '$keyToCheck' does not exist in the array.";
}
使用 isset()
isset() 除了检查键是否存在外,还会检查该键的值是否不是 null。
$array = [
'name' => 'Alice',
'age' => 30,
'city' => 'New York'
];
$keyToCheck = 'age';
if (isset($array[$keyToCheck])) {
echo "Key '$keyToCheck' exists in the array and its value is not null.";
} else {
echo "Key '$keyToCheck' does not exist in the array or its value is null.";
}
区别
array_key_exists(): 仅检查键是否存在,不关心值是否为 null。
isset(): 检查键是否存在且其值不为 null。
选择使用哪种方法取决于你的具体需求。如果你只想确认键是否存在而不关心其值,使用 array_key_exists()。如果你需要确认键存在且其值不为 null,使用 isset()。