John Dale Ocaya Andil Dale John Dale Ocaya Andil Dale - 11 months ago 110
PHP Question

php checking if value exist in a 2 level multidimensional array

I have this array:

Array
(
[01] => Array
(
[cat_id] => 15
[offset] => 4951
)

[02] => Array
(
[cat_id] => 15
[offset] => 4251
)

[03] => Array
(
[cat_id] => 15
[offset] => 4001
)

[04] => Array
(
[cat_id] => 15
[offset] => 4951
)

[05] => Array
(
[cat_id] => 15
[offset] => 3301
)
)


I have the code to get the key on first level using array_key_exists;

if ((array_key_exists("01", $completed_steps))) {
echo "Found 0!";
}


But I want now to get the cat_id value, how could I do that in a level 2 array?

Answer Source

Use below code, it will find key to n-level depth and search for given key

function multiKeyExists(array $arr, $key) {

    // is in base array?
    if (array_key_exists($key, $arr)) {
        return $arr[$key]['cat_id']; // returned cat_id 
    }

    // check arrays contained in this array
    foreach ($arr as $element) {
        if (is_array($element)) {
            if (multiKeyExists($element, $key)) {
                return $element[$key]['cat_id']; // returned cat_id
            }
        }

    }

    return false;
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download