Easily Check if Multiple Array Keys Exist in PHP

Today I found myself needing to check an associative array to see if it contained a specific set of keys.

Here is what I was wanting to do:

if( isset( $data['sanitize'], $data['validate'], $data['authorize'] ) ) {
    // Do stuff with my special array data
}

Granted, it isn’t a whole lot of code, but syntax like this just drives me nuts. So, I thought, wouldn’t it be nice to do something like this instead:

if( array_keys_exist( $data, 'sanitize', 'validate', 'authorize' ) ) {
    // Do stuff with my special array data
}

This plays off of the well known array_key_exists() function in PHP, but adds in the ability to check if multiple keys exist and improves the readability of the code.

So, moments later, I put together a nice little utility function that does just that:

/**
 * Checks if multiple keys exist in an array
 *
 * @param array $array
 * @param array|string $keys
 *
 * @return bool
 */
function array_keys_exist( array $array, $keys ) {
    $count = 0;
    if ( ! is_array( $keys ) ) {
        $keys = func_get_args();
        array_shift( $keys );
    }
    foreach ( $keys as $key ) {
        if ( isset( $array[$key] ) || array_key_exists( $key, $array ) ) {
            $count ++;
        }
    }

    return count( $keys ) === $count;
}

Enjoy!

Comments

  1. Hi,

    the method call should be
    array_keys_exist( $data, [‘sanitize’, ‘validate’, ‘authorize’] )

    and I suggest fit to array_key_exists convention and switch array and keys….

    -toretak

    1. Thanks for the feedback!

      Actually, you can either pass in an array as the second parameter, or just a bunch of individual params. It will work either way.

      I did consider following the same pattern as array_key_exists(), but ultimately I liked being able to pass a bunch of single params instead of having to create and pass in an array. I occasionally have to run code on sites where the bracket syntax for arrays isn’t supported, so I usually just use the array() syntax. I like having things be super easy to read, so the individual params met that goal.

      However, these are just my thoughts and approach… I’m glad you are using them for inspiration and adapting them to fit your needs. If I were trying to release this function into a public library or framework, I’d probably make the change you suggested.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.