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:
JavaScript
x
array=>[
'name'=>'jack'
, 'age'=>'18'
, 'info'=>[
'address'=>'bla bla bla'
, 'email'=>'example@bla.com'
]
]
JavaScript
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?
Advertisement
Answer
Try using recursive function:
JavaScript
<?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”