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