Skip to content

Instantly share code, notes, and snippets.

@thibaut-decherit
Forked from thomasmerlin/index.php
Created March 15, 2019 11:20
Show Gist options
  • Save thibaut-decherit/334a0baf80b0d08188153b9011090d12 to your computer and use it in GitHub Desktop.
Save thibaut-decherit/334a0baf80b0d08188153b9011090d12 to your computer and use it in GitHub Desktop.
[PHP] - Getting array max depth | Disclaimer & Warning : This function may not handle every case, but works for almost basic ones.
<?php
// Function
/**
* Get the array max depth.
*
* @param array $array
*
* @return int
*/
private function getArrayMaxDepth(array $array): int
{
$maxDepth = 1;
foreach ($array as $key => $value) {
$elementDepth = 2;
while (is_array($value) === true) {
foreach ($value as $subValue) {
if (is_array($subValue) === true) {
$elementDepth++;
if ($elementDepth > $maxDepth) {
$maxDepth = $elementDepth;
}
}
$value = $subValue;
}
}
}
return $maxDepth;
}
// Tests
$array1 = [
// First depth level
'easy_admin' => [
// Second level
'entities' => [
// Third level
'Product' => [
// Fourth level
'class' => 'App\Entity\Product'
]
]
]
];
$array2 = [
'key1-1' => [
'key1-2' => [
'key1-3' => [
'key1-4-1' => 'Not an array, should stop counting here.'
]
]
],
'key2-1' => [
'key2-2' => [
'key2-3' => [
'key2-4' => [
'key2-5' => [
'key2-6' => [
'key2-7' => 'Not an array, should stop counting here.'
]
]
]
]
]
]
];
echo "First array's depth : " . getArrayMaxDepth($array1) . "\n"; // Returns 4 (integer).
echo "Second array's depth : " . getArrayMaxDepth($array2); // Returns 7 (integer).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment