How to check if multiple array keys exists

2019-01-29 23:01发布

I have a variety of arrays that will either contain

story & message

or just

story

How would I check to see if an array contains both story and message? array_key_exists() only looks for that single key in the array.

Is there a way to do this?

标签: php key
18条回答
狗以群分
2楼-- · 2019-01-29 23:12

The above solutions are clever, but very slow. A simple foreach loop with isset is more than twice as fast as the array_intersect_key solution.

function array_keys_exist($keys, $array){
    foreach($keys as $key){
        if(!array_key_exists($key, $array))return false;
    }
    return true;
}

(344ms vs 768ms for 1000000 iterations)

查看更多
疯言疯语
3楼-- · 2019-01-29 23:13

One more solution in the collection:

if (!array_diff(['story', 'message'], array_keys($array))) {
    // OK: all keys are in the $array
} else {
   // FAIL: not all keys found
}
查看更多
ゆ 、 Hurt°
4楼-- · 2019-01-29 23:17

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);
}
查看更多
可以哭但决不认输i
5楼-- · 2019-01-29 23:18

Here is a solution that's scalable, even if you want to check for a large number of keys:

<?php

// The values in this arrays contains the names of the indexes (keys) 
// that should exist in the data array
$required = array('key1', 'key2', 'key3');

$data = array(
    'key1' => 10,
    'key2' => 20,
    'key3' => 30,
    'key4' => 40,
);

if (count(array_intersect_key(array_flip($required), $data)) === count($required)) {
    // All required keys exist!
}
查看更多
地球回转人心会变
6楼-- · 2019-01-29 23:18

What about this:

isset($arr['key1'], $arr['key2']) 

only return true if both are not null

if is null, key is not in array

查看更多
在下西门庆
7楼-- · 2019-01-29 23:18

try this

$required=['a','b'];$data=['a'=>1,'b'=>2];
if(count(array_intersect($required,array_keys($data))>0){
    //a key or all keys in required exist in data
 }else{
    //no keys found
  }
查看更多
登录 后发表回答