我有一种情况,我想检查PHP数组中的2级密钥。所以我的代码目前看起来像......
if(array_key_exists($needleBox, $haystack)) {
if(array_key_exists($needle, $haystack[$needleBox])) {
// do stuff with value attached to $needle
}
}
我首先检查包含我的针($needleBox
)的数组,然后检查针是否找到$needleBox
。
跳过检查$needleBox
并使用是否安全...
if(array_key_exists($needle, $haystack[$needleBox])) {
// do stuff with value attached to $needle
}
或者在一个if
声明中检查两者,如...
if(array_key_exists($needleBox, $haystack) && array_key_exists($needle, $haystack[$needleBox])) {
// do stuff with value attached to $needle
}
我认为第一种选择更为简洁。
为什么你不使用isset
。我更喜欢它.. isset
比array_key_exists
快得多。如果值为null,BTW isset
将返回false。
if (isset($haystack[$needleBox]) && isset($haystack[$needleBox][$needle])) {
//code
}
EDIT同意@shawn的建议
if (isset($haystack[$needleBox][$needle])) {
//code
}