Alex
Alex

Reputation: 67698

PHP in_array_keys-like function

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

Upvotes: 1

Views: 1826

Answers (3)

Francois Deschenes
Francois Deschenes

Reputation: 24989

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).

Upvotes: 4

Jasper
Jasper

Reputation: 76003

There happens to be just that:

array_key_exists()

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

Upvotes: 2

Alexander Gessler
Alexander Gessler

Reputation: 46637

It is named array_key_exists.

Upvotes: 8

Related Questions