扫描二维码下载沐宇APP

沐宇

微信扫码使用沐宇小程序

沐宇

php怎么判断key是否存在

扬州沐宇科技
2024-02-29 15:50:19
PHP

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

扫码添加客服微信