Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multidimensional PHP array - Key exists

I want a function that will return TRUE or FALSE based on if a given key exists in a multidimensional array in PHP.

I haven't been able to figure out a recursive function to perform this action.

A sample of what this could do:

$array = array(
    'key 1' => array(
        'key 1.1' => array()
        'key 1.2' => array()
    ),
    'key 2' => array(
        'key 2.1' => array(
            'key 2.1.1' => array()
        )
        'key 2.2' => array()
    )
);

multi_array_key_exists('key 1', $array); // return TRUE

multi_array_key_exists('key 2.1.1', $array); // return TRUE

multi_array_key_exists('key 3', $array); // return FALSE
like image 704
Mr. Meeseeks Avatar asked Mar 20 '26 02:03

Mr. Meeseeks


2 Answers

This is where a recursive function comes in handy.

function multi_array_key_exists($key, array $array): bool
{
    if (array_key_exists($key, $array)) {
        return true;
    } else {
        foreach ($array as $nested) {
            if (is_array($nested) && multi_array_key_exists($key, $nested))
                return true;
        }
    }
    return false;
}

Note that this can take some time (in long nested arrays), it might be better to flatten first, since you are only interested in whether the key exists or not.

like image 136
kero Avatar answered Mar 22 '26 13:03

kero


Maybe too late but here's a solution I came up with:

function multi_array_key_exists(array $path, array $array): bool
{
    if (empty($path)) {
        return false;
    }
    foreach ($path as $key) {
        if (isset($array[$key]) || array_key_exists($key, $array)) {
            $array = $array[$key];
            continue;
        }

        return false;
    }

    return true;
}

$testMe = ['my' => ['path' => ['exists' => true]]];
multi_array_key_exists(['my', 'path', 'exists'], $testMe);

I does not need costly recursive calls and is slightly faster (~15% on my setup).

like image 43
xlttj Avatar answered Mar 22 '26 13:03

xlttj