-1

find items level(depth) in array;

hi im new in php and i cant find any method to find what dimension array items are in. for example:

array=>[
  'name'=>'jack'
  , 'age'=>'18'
  , 'info'=>[
    'address'=>'bla bla bla'
    , 'email'=>'example@bla.com'
  ]
]

function findDepth($key)
{
  // do something
}

$result = findDepth('email');

$result // int(2)

the array above has key named email and the email key is in second level of the array. is there any function or method or way to find this level.

I found a method that tell you how deep array is: Is there a way to find out how "deep" a PHP array is?

ErfanQSN
  • 15
  • 3

2 Answers2

1

Try using recursive function:

<?php

$array = [
    'name'=>'jack', // Level 0
    'age'=>'18',
    'info'=>[ // Level 1
        'address'=>'bla bla bla',
        'contacts' => [ // Level 2
            'email'=>'example@bla.com'
        ],
    ],
];

function getArrayKeyDepth(array $array, $key, int $currentDepth = 0): ?int
{
    foreach($array as $k => $v){
        if ($key === $k) {
            return $currentDepth;
        }
        
        if (is_array($v)) {
            $d = getArrayKeyDepth($v, $key, $currentDepth + 1);
            
            if ($d !== null) {
                return $d;
            }
        }
    }
    
    return null;
}

echo "Result:  ". getArrayKeyDepth($array, 'email');

This will give you "Result: 2"

Alex Smith
  • 311
  • 1
  • 3
  • 14
0

Use a recursive function.

function findDepth(array $array, string $key, int $level = 0) : ?int
{
    $level++;
    foreach($array as $k=>$row){
        if($k == $key) return $level;
        if(is_array($row) && $c = findDepth($row, $key, $level)) return $c;
    }
    return null;
}

This will return only the first key match so if you had another email key in the root of your array further down in the index, you would still only get 2 as the result.

Working sample: http://sandbox.onlinephpfunctions.com/code/3d5847fa8f67cd52f5f95eccefa75359a721edc0

Esben Tind
  • 885
  • 4
  • 14