Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?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).
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement