Leon Armstrong Leon Armstrong - 9 months ago 52
PHP Question

How to search array at certain depth?

I am having a multidimensional array with many depth , since I have around 9 dimension so I going to show my code on how I accessing them

sample code:


sample array

Is there any way to get the array base on the depth and key I want , without knowing the level before it

lets say I have only partial information like key 20(the last key) , Is there any way to get the array at the 9th dimension with key 20?

Ideal function should look like this

function get_by_depth($m_array,$depth,$key){


//will search through available level 9 item
//if there are key 20 at level 9 return the array or value

Answer Source

Something like this could work using your sample array data.

function get_by_depth($array, $depth, $key, $currentDepth = 0)
    if ($currentDepth == $depth) {

        return isset($array[$key]) ? $array[$key] : null;

    } else {

        foreach ($array as $k => $v) {

            if (is_array($v)) {
                return get_by_depth($v, $depth, $key, ++$currentDepth);




echo "<pre>";

Note This assumes that every array only contains at most a single array inside of it. If you need a solution that can handle arrays that contain multiple arrays at the same level of depth then there would be a lot more work to do