How to Find Out How "Deep" a PHP Array Is

Is there a way to find out how deep a PHP array is?

This should do it:

<?php

function array_depth(array $array) {
$max_depth = 1;

foreach ($array as $value) {
if (is_array($value)) {
$depth = array_depth($value) + 1;

if ($depth > $max_depth) {
$max_depth = $depth;
}
}
}

return $max_depth;
}

?>

Edit: Tested it very quickly and it appears to work.

How to find the depth of an unlimited depthed array

Try this man

                function array_depth($array, $n = 0) {
$max_depth = 1;
foreach ($array as $value) {
if (isset($value['subcategories'][0])) {
$depth = $this -> array_depth($value['subcategories']) + 1;
if ($depth > $max_depth) {
$max_depth = $depth;
}
}
}
return $max_depth;
}

Array PHP. How to get deep of element in array

You can use the following recursive function to get the depth where the uuid value is found. This version returns value 0 if the uuid value is not found at all.

function searchDepth($uid, $array, $depth = 0)
{
$depth++;

foreach ($array as $element)
{
if (isset($element['uid']) && $element['uid'] == $uid)
{
return $depth;
}
else if (isset($element['introducer_users']))
{
$result = searchDepth($uid, $element['introducer_users'], $depth);

if ($result != 0)
{
return $result;
}
}
}

return 0;
}

And to invoke the function with the search uuid and the array

$depth = searchDepth(10, $mang);

How to check if a deep array value is present

The following will work as you expect:

if(isset($a['a']['b']['c']))

If any of those elements are undefined, isset() will return false.

How to set a deep array in PHP

This one should work. Using this function you can set any array element in any depth by passing a single string containing the keys separated by .

function setArray(&$array, $keys, $value) {
$keys = explode(".", $keys);
$current = &$array;
foreach($keys as $key) {
$current = &$current[$key];
}
$current = $value;
}

You can use this as follows:

$array = Array();
setArray($array, "key", Array('value' => 2));
setArray($array, "key.test.value", 3);
print_r($array);

output:

Array (
[key] => Array
(
[value] => 2
[test] => Array
(
[value] => 3
)

)

)

How to search array at certain depth?

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>";
print_r(get_by_depth($array,8,'image'));exit;

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



Related Topics



Leave a reply



Submit