How to check if multiple array keys exists

前端 未结 1 902
时光取名叫无心
时光取名叫无心 2020-12-22 20:50

I have a variety of arrays that will either contain

story & message

or just

story

How would I check

相关标签:
1条回答
  • 2020-12-22 21:40

    If you only have 2 keys to check (like in the original question), it's probably easy enough to just call array_key_exists() twice to check if the keys exists.

    if (array_key_exists("story", $arr) && array_key_exists("message", $arr)) {
        // Both keys exist.
    }
    

    However this obviously doesn't scale up well to many keys. In that situation a custom function would help.

    function array_keys_exists(array $keys, array $arr) {
       return !array_diff_key(array_flip($keys), $arr);
    }
    
    0 讨论(0)
提交回复
热议问题