(PHP 4 >= 4.0.7, PHP 5)
array_key_exists — 檢查給定的鍵名或索引是否存在于數組中
說明
bool array_key_exists ( mixed$key
, array $search
)
array_key_exists() 在給定的 key
存在于數組中時返回 TRUE
。key
可以是任何能作為數組索引的值。array_key_exists()
也可用于對象。
參數
key
要檢查的鍵。
search
一個數組,包含待檢查的鍵。
返回值
成功時返回 TRUE
, 或者在失敗時返回 FALSE
。
范例
Example #1 array_key_exists() 例子
<?php
$search_array = array('first' => 1, 'second' => 4);
if (array_key_exists('first', $search_array)) {
echo "The 'first' element is in the array";
}
?>
Example #2 array_key_exists() 與 isset() 的對比
isset() 對于數組中為 NULL
的值不會返回 TRUE
,而
array_key_exists() 會。
<?php
$search_array = array('first' => null, 'second' => 4);
// returns false
isset($search_array['first']);
// returns true
array_key_exists('first', $search_array);
?>
注釋
Note:
為了向下兼容,可以使用下列已廢棄的別名: key_exists()
Note:
For backward compatibility reasons, array_key_exists()
will also return TRUE
if key
is a property
defined within an object given as
search
. This behaviour should not be relied upon,
and care should be taken to ensure that search
is
an array.
To check whether a property exists in an object, use property_exists().
參見
isset() - 檢測變量是否設置 array_keys() - 返回數組中所有的鍵名 in_array() - 檢查數組中是否存在某個值 property_exists() - 檢查對象或類是否具有該屬性