假设我有一个数组,其元素如下所示:
$elements = array(
"Canada" => "Ottawa",
"France" => "Paris",
...
);
Run Code Online (Sandbox Code Playgroud)
如何检查"Canada" => "Ottawa"此数组中是否存在?
在文档中的“ 数组函数 ”列表中查找,我看不到任何内置函数可以做到这一点。但是,为它滚动自己的实用程序功能很容易:
/*
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;
}
Run Code Online (Sandbox Code Playgroud)
用法示例:
$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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5206 次 |
| 最近记录: |