Is there a similar function like in_array() but that can check array keys, instead of values?
3 Answers
5 Comments
GolezTrol
Good answer, great function. :)
Alex
but it's not the same, you can only check a string
@Alex: From PHP.net:
key can be any value possible for an array index.Alex
so can I use
array_key_exists(array('abc', 'xyz'), array('abc' => 343, 'xyz' => 3434, 'def' => 343434) ?Based on the comment you left on @Alexander Gessler's answer, here's a small function you could use:
function array_keys_exist(array $keys, array $array)
{
// Loop through all the keys and if one doesn't exist, return false.
foreach ( $keys as $key )
if ( ! array_key_exists($key, $array) )
return false;
// All keys were found.
return true;
}
if ( array_keys_exist(array('abc', 'xyz'), array('abc' => 343, 'xyz' => 3434, 'def' => 343434)) )
echo 'All keys exist!';
The function above called array_keys_exist loops through all the keys in the keys array calling PHP's array_key_exists function and if a key isn't found the function returns false (or true if all the keys were found in the array).
Comments
There happens to be just that:
array_key_exists()
Found on the php docs: http://php.net/manual/en/function.array-key-exists.php
in_arraylinks toarray_key_exists