Guest User

Untitled

a guest
Mar 20th, 2019
59
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <?php
  2. // Function
  3. /**
  4. * Get the array max depth.
  5. *
  6. * @param array $array
  7. *
  8. * @return int
  9. */
  10. private function getArrayMaxDepth(array $array): int
  11. {
  12. $maxDepth = 1;
  13.  
  14. foreach ($array as $key => $value) {
  15. $elementDepth = 2;
  16. while (is_array($value) === true) {
  17. foreach ($value as $subValue) {
  18. if (is_array($subValue) === true) {
  19. $elementDepth++;
  20. if ($elementDepth > $maxDepth) {
  21. $maxDepth = $elementDepth;
  22. }
  23. }
  24. $value = $subValue;
  25. }
  26. }
  27. }
  28.  
  29. return $maxDepth;
  30. }
  31.  
  32. // Tests
  33.  
  34. $array1 = [
  35. // First depth level
  36. 'easy_admin' => [
  37. // Second level
  38. 'entities' => [
  39. // Third level
  40. 'Product' => [
  41. // Fourth level
  42. 'class' => 'App\Entity\Product'
  43. ]
  44. ]
  45. ]
  46. ];
  47.  
  48. $array2 = [
  49. 'key1-1' => [
  50. 'key1-2' => [
  51. 'key1-3' => [
  52. 'key1-4-1' => 'Not an array, should stop counting here.'
  53. ]
  54. ]
  55. ],
  56. 'key2-1' => [
  57. 'key2-2' => [
  58. 'key2-3' => [
  59. 'key2-4' => [
  60. 'key2-5' => [
  61. 'key2-6' => [
  62. 'key2-7' => 'Not an array, should stop counting here.'
  63. ]
  64. ]
  65. ]
  66. ]
  67. ]
  68. ]
  69. ];
  70.  
  71. echo "First array's depth : " . getArrayMaxDepth($array1) . "\n"; // Returns 4 (integer).
  72. echo "Second array's depth : " . getArrayMaxDepth($array2); // Returns 7 (integer).
RAW Paste Data