Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check array for multiple keys

Tags:

php

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";
}
?>
like image 649
jmenezes Avatar asked Jul 18 '26 16:07

jmenezes


2 Answers

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
}
?>
like image 174
underscore Avatar answered Jul 20 '26 06:07

underscore


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

like image 40
Gauthier Avatar answered Jul 20 '26 06:07

Gauthier