3

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";
}
?>

3 Answers 3

5

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
}
?>
Sign up to request clarification or add additional context in comments.

1 Comment

split is a deprecated function. Use explode.
2

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

2 Comments

You should probably include the example function array_key_exists_r from the comment on php.net, otherwise it seems like this is a default solution.
Renaming that function to areset to use as replacement for isset makes it much more comformable to type repeatedly. And yes, I know isset returns false when the value of the key is null.
1
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.