Suppose there is a random php array:

$array = [[1, 2],[2, 3, [3, 4]], [[2, [3, [a, b]], [2, 5]], [2, 6, 3]]]; 

How to find out the level of the maximum nested element? Those. nesting is now - level 4, these are elements of [a, b];

2 answers 2

The main thing we need is is_array() .

 $array = [[1, 2],[2, 3, [3, 4]], [[2, [3, [0, 0]], [2, 5]], [2, 6, 3]]]; function get_lvl(array $array) { $max_lvl = 1; foreach ($array as $value) { if (is_array($value)) { $lvl= get_lvl($value) + 1; if ($lvl> $max_lvl) { $max_lvl = $lvl; } } } return $max_lvl; } echo get_lvl($array); 

Thank you for helping @Other , but the essence of the problem solution remains the same :)

  • OK, then add one array to the root of the array and see the irregularity! - user207618 5:59 pm
  • 3
    Copy from here: stackoverflow.com/q/262891/6275986 - user207618
  • Yes, I need a nesting level. I have a, b pointed for example - they are the deepest elements in the array. - azhirov1991
  • @Other yes, your decision helped. Thank you very much! stackoverflow.com/questions/262891/… - azhirov1991
  • @ azhirov1991, You're welcome. - user207618

How to find out the level of the maximum nested element? Those. nesting now - level 4

You can use the getDepth() method of the RecursiveIteratorIterator class:

 $array = [[1, 2],[2, 3, [3, 4]], [[2, [3, ['a', 'b']], [2, 5]], [2, 6, 3]]]; echo get_depth($array); 

Result: 4

 function get_depth(Array $arr, $depth = 0): Int { $it = new RecursiveIteratorIterator(new RecursiveArrayIterator($arr)); foreach ($it as $tmp) { $int = $it->getDepth(); $depth >= $int ?: $depth = $int; } return $depth; }