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:

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:

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:

Enjoy!

2 thoughts on “Easily Check if Multiple Array Keys Exist in PHP”

  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 *