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!