2014-09-01 68 views
0

假設我有一個數組,其元素是這樣的:檢查關聯數組包含鍵值對

$elements = array(
    "Canada" => "Ottawa", 
    "France" => "Paris", 
    ... 
); 

我如何檢查是否"Canada" => "Ottawa"存在這個數組中?

+4

'$元素[$國家] == $ capitale'? – kero 2014-09-01 16:58:07

+0

@kingkero如果'$ country'不是數組中的鍵,將會拋出'Undefined offset'通知。 – 2014-09-01 19:00:55

回答

2
if (isset($elements[$country]) AND $elements[$country] == $capitale) { 
    return true; 
} 
return false; 
1

向下看的Array Functions在文檔列表中,我沒有看到內置在做這種事。但它很容易推出自己的效用函數爲它:

/* 
    Returns true if the $key exists in the haystack and its value is $value. 

    Otherwise, returns false. 
*/ 
function key_value_pair_exists(array $haystack, $key, $value) { 
    return array_key_exists($key, $haystack) && 
      $haystack[$key] == $value; 
} 

用法示例:

$countries_to_capitals = [ 
    'Switzerland' => 'Bern', 
    'Nepal' => 'Kathmandu', 
    'Canada' => 'Ottawa', 
    'Australia' => 'Canberra', 
    'Egypt' => 'Cairo', 
    'Mexico' => 'Mexico City' 
]; 
var_dump(
    key_value_pair_exists($countries_to_capitals, 'Canada', 'Ottawa') 
); // true 
var_dump(
    key_value_pair_exists($countries_to_capitals, 'Switzerland', 'Geneva') 
); // false 
相關問題