Skip to content
Advertisement

Check if specific array key exists in multidimensional array – PHP

I have a multidimensional array e.g. (this can be many levels deep):

$array = Array ( 
    [21] => Array ( ) 
    [24] => Array ( 
        [22] => Array ( ) 
        [25] => Array ( 
            [26] => Array ( ) 
        ) 
    ) 
) 

I am trying to loop through it to see if a certain key exists:

$keySearch = 22; // key searching for

function findKey($array, $keySearch) {
    foreach ($array as $item){
        if (isset($item[$keySearch]) && false === findKey($item[$keySearch], $item)){
            echo 'yes, it exists';
        }
    }
}

findKey($array, $keySearch);

But it finds nothing. Is there an error in the loop?

Advertisement

Answer

I played with your code to get it working :

function findKey($array, $keySearch)
{
    foreach ($array as $key => $item) {
        if ($key == $keySearch) {
            echo 'yes, it exists';
            return true;
        } elseif (is_array($item) && findKey($item, $keySearch)) {
            return true;
        }
    }
    return false;
}
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement