Reputation: 1926
Is it possible to check in one go if multiple keys exists in an array, instead of using the array_key_exists
function multiple times? Or, can this be achieved another way?
<?php
$search_array = array('first' => 1, 'second' => 4);
if(array_key_exists('first','second' $search_array))//Do something like this.
{
echo "The 'first' element is in the array";
}
?>
Upvotes: 3
Views: 3956
Reputation: 6887
See https://web.archive.org/web/20130527004746/http://php.net/manual/en/function.array-key-exists.php.
One note says
this function very good to use if you need to verify many variables:
<?php function array_key_exists_r($keys, $search_r) { $keys_r = split('\|',$keys); foreach($keys_r as $key) if(!array_key_exists($key,$search_r)) return false; return true; } ?> e.g. <?php if(array_key_exists_r('login|user|passwd',$_GET)) { // login } else { // other } ?>
Upvotes: 5
Reputation: 1321
Not an out of the box function, The solution by Samitha Hewawasam has if fully commented.
if(array_key_exists_r('first|second',$search_array)) {
// searching for items in array
} else {
// other
}
This should help you out. It will search for your items seperated by pipes (|) I pull this from http://php.net/manual/en/function.array-key-exists.php
Upvotes: 2
Reputation: 23777
function keysInArray ($array, $keys) {
foreach ($keys as $key)
if (!array_key_exists($key, $array))
return false; // failure, if any key doesn't exist
return true; // else true; it hasn't failed yet
}
And call it with:
if (keysInArray($searchArray, array("key1", "key2", /*...*/))) { /* ... */ }
And yes, you have to use multiple checks (e.g. in a loop); there doesn't exist an all-in-one function.
Upvotes: 1