1

Is there a similar function like in_array() but that can check array keys, instead of values?

1
  • 4
    -1 because the php.net page for in_array links to array_key_exists Commented Jun 24, 2011 at 22:54

3 Answers 3

8

It is named array_key_exists.

Sign up to request clarification or add additional context in comments.

5 Comments

Good answer, great function. :)
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.
so can I use array_key_exists(array('abc', 'xyz'), array('abc' => 343, 'xyz' => 3434, 'def' => 343434) ?
@Alex the documentation doesn't say, so I'm assuming no, but you could always just use the function in a for loop to get the same result.
4

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

2

There happens to be just that:

array_key_exists()

Found on the php docs: http://php.net/manual/en/function.array-key-exists.php

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.