Smiley Happy Coder

Simple method to test if a key exists in a multidimensional array.

I’ve used this function/method a few times over the years so I thought I’d jot it down to save future me some headaches.

Sometimes I have needed to check an array to see if the key exists within it. One solution might be to just check if that key is set.

if ( isset( $array['key'])) {

The issue with this method is that I might not know what the key is called or even if it exists at the top level of the array. It could be a multidimensional array, it might not be.

So I wrote a wee function to help out. In this case I’m in a Laravel project so its a public static function in a Helpers repository.

You’ll see that the first thing that goes on is to check if the key exists at the top level of the array, if found the function will return. No sense battling on if we already have our answer.

The second thing I do is to loop over the items in the array and, should that item be an array, perform that same test and return, if nothing is found then return false.

I could have abstracted the ‘array_key_exists’ chunk off to a different method to dave duplication but I feel thats just a step too far.

/**
 * Simple method, pass a key then the array
 * Method will return a bool
 * 
 * @param $key
 * @param $array
 *
 * @return bool
 */
public function testIfKeyExistsInArray( $key , $array )
{
    if ( array_key_exists ($key, $array) ) {
        return true;
    }

    //If the item is an array, then dig into it...
    foreach( $array as $item ){
        if ( gettype($item) === 'array'){
            if ( array_key_exists($key , $item)){
                return true;
            }
        }
    }

    return false;
}

Example usage

if ( Helper::testIfKeyExistsInArray( 'add_another' , $request->all() )){
    //Do whatever here
}

Limitations

The isn’t a very intelligent method by any means, it literally just looks one level deep if the item is an array.

I’m 100% sure there are many many ways to skin this cat. But this does work.