在PHP中,isset() 函數用于檢查一個變量是否已經設置以及是否不為 NULL。要檢查數組鍵是否存在,可以使用以下方法:
<?php
$array = array(
'key1' => 'value1',
'key2' => 'value2',
);
if (isset($array['key1'])) {
echo "Key 'key1' exists and its value is: " . $array['key1'];
} else {
echo "Key 'key1' does not exist.";
}
if (isset($array['key3'])) {
echo "Key 'key3' exists and its value is: " . $array['key3'];
} else {
echo "Key 'key3' does not exist.";
}
?>
輸出結果:
Key 'key1' exists and its value is: value1
Key 'key3' does not exist.
在這個例子中,我們首先創建了一個包含兩個鍵值對的數組。然后,我們使用 isset() 函數檢查數組中是否存在特定的鍵。如果存在,我們輸出相應的值,否則輸出該鍵不存在的信息。