温馨提示×

php怎么判断key是否存在

PHP
小亿
101
2024-02-29 15:50:19
栏目: 编程语言

在PHP中,可以使用array_key_exists()函数来判断一个key是否存在于数组中。示例如下:

$array = array("name" => "John", "age" => 30, "city" => "New York");

if (array_key_exists("name", $array)) {
    echo "Key 'name' exists in the array";
} else {
    echo "Key 'name' does not exist in the array";
}

另外,也可以使用isset()函数来判断一个key是否存在于数组中。示例如下:

$array = array("name" => "John", "age" => 30, "city" => "New York");

if (isset($array["name"])) {
    echo "Key 'name' exists in the array";
} else {
    echo "Key 'name' does not exist in the array";
}

array_key_exists()和isset()函数的区别在于isset()函数在key存在且对应的值不为null时返回true,而array_key_exists()函数只判断key是否存在。

0