How to find the maximum depth an array is in PHP

1 Answer

0 votes
function getArrayDepth(array $array): int {
    $maxDepth = 1; // Start with depth of 1

    foreach ($array as $value) {
        if (is_array($value)) {
            // Recursively calculate the depth of nested arrays
            $maxDepth = max($maxDepth, getArrayDepth($value) + 1);
        }
    }

    return $maxDepth;
}

$array = [
    1,
    [2, 3],
    [4, [5, 6, [7]]],
    8
];

print_r($array);

echo "\nThe array depth is: " . getArrayDepth($array);



/*
run:

Array
(
    [0] => 1
    [1] => Array
        (
            [0] => 2
            [1] => 3
        )

    [2] => Array
        (
            [0] => 4
            [1] => Array
                (
                    [0] => 5
                    [1] => 6
                    [2] => Array
                        (
                            [0] => 7
                        )

                )

        )

    [3] => 8
)

The array depth is: 4

*/

 



answered Apr 5, 2025 by avibootz
...