0
假設我有一個數組,其元素是這樣的:檢查關聯數組包含鍵值對
$elements = array(
"Canada" => "Ottawa",
"France" => "Paris",
...
);
我如何檢查是否"Canada" => "Ottawa"
存在這個數組中?
假設我有一個數組,其元素是這樣的:檢查關聯數組包含鍵值對
$elements = array(
"Canada" => "Ottawa",
"France" => "Paris",
...
);
我如何檢查是否"Canada" => "Ottawa"
存在這個數組中?
if (isset($elements[$country]) AND $elements[$country] == $capitale) {
return true;
}
return false;
向下看的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
'$元素[$國家] == $ capitale'? – kero 2014-09-01 16:58:07
@kingkero如果'$ country'不是數組中的鍵,將會拋出'Undefined offset'通知。 – 2014-09-01 19:00:55