php嵌套检查数组键

问题描述 投票:0回答:1

我有一种情况,我想检查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
    }

我认为第一种选择更为简洁。

php arrays
1个回答
1
投票

为什么你不使用isset。我更喜欢它.. issetarray_key_exists快得多。如果值为null,BTW isset将返回false。

if (isset($haystack[$needleBox]) && isset($haystack[$needleBox][$needle])) {
     //code
}

EDIT同意@shawn的建议

if (isset($haystack[$needleBox][$needle])) {
     //code
}
© www.soinside.com 2019 - 2024. All rights reserved.