Quantcast
Channel: How to check if multiple array keys exists - Stack Overflow
Viewing all articles
Browse latest Browse all 22

Answer by Oluwatobi Samuel Omisakin for How to check if multiple array keys exists

$
0
0

Something as this could be used

//Say given this array$array_in_use2 = ['hay' => 'come', 'message' => 'no', 'story' => 'yes'];//This gives either true or false if story and message is therecount(array_intersect(['story', 'message'], array_keys($array_in_use2))) === 2;

Note the check against 2, if the values you want to search is different you can change.

This solution may not be efficient, but it works!

Updates

In one fat function:

 /** * Like php array_key_exists, this instead search if (one or more) keys exists in the array * @param array $needles - keys to look for in the array * @param array $haystack - the <b>Associative</b> array to search * @param bool $all - [Optional] if false then checks if some keys are found * @return bool true if the needles are found else false. <br> * Note: if hastack is multidimentional only the first layer is checked<br>, * the needles should <b>not be<b> an associative array else it returns false<br> * The array to search must be associative array too else false may be returned */function array_keys_exists($needles, $haystack, $all = true){    $size = count($needles);    if($all) return count(array_intersect($needles, array_keys($haystack))) === $size;    return !empty(array_intersect($needles, array_keys($haystack)));}

So for example with this:

$array_in_use2 = ['hay' => 'come', 'message' => 'no', 'story' => 'yes'];//One of them exists --> true$one_or_more_exists = array_keys_exists(['story', 'message'], $array_in_use2, false);//all of them exists --> true$all_exists = array_keys_exists(['story', 'message'], $array_in_use2);

Viewing all articles
Browse latest Browse all 22

Trending Articles