温馨提示×

php怎么判断key是否存在

PHP
小亿
149
2024-02-29 15:50:19
栏目: 编程语言
PHP开发者专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在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是否存在。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:PHP key_exists函数:高效判断数组键是否存在

0