-1

Currently, I am looping through 4 foreach loops:

foreach ($level0_array as $level0_key => $level1_array) {
    //do something
    foreach ($level1_array as $level1_key => $level2_array) {
        //do something
        foreach ($level2_array as $level2_key => $level3_array) {
            //do something
            foreach ($level3_array as $level3_key => $level4_value) {
                //do something
            }
        }
    }
}

Is it possible to do it if this loop is inside a function and it is supposed to get the number of levels to loop through dynamically? (Assuming in this case that $level0_array have enough levels in it)

i.e.

function ($level0_array, $number_of_levels) {
    // loop. . .
}
Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
pileup
  • 1
  • 2
  • 18
  • 45
  • 2
    **Hint**: recursive function. – Blackhole Dec 29 '22 at 12:42
  • @Blackhole The thing I was afraid of :}, ever since they made us program Hanoi Towers with recursion back in university – pileup Dec 29 '22 at 12:43
  • 1
    [Is there a way to loop through a multidimensional array without knowing it's depth?](https://stackoverflow.com/questions/10928993/is-there-a-way-to-loop-through-a-multidimensional-array-without-knowing-its-dep) – Alive to die - Anant Dec 29 '22 at 12:43
  • @Anant-Alivetodie, thanks, looks similar to my question, will take a look, if it is then mine could be a duplicate – pileup Dec 29 '22 at 12:44

1 Answers1

2

Yes, there is, and it is called recursion:

function loopThroughLevels($level_array, $number_of_levels_left) {
     foreach ($level_array as $level_key => $level_value) {
         // do something
         if (is_array($level_value) &&
             ($number_of_levels_left > 0)) {
             loopThroughLevels($level_value, $number_of_levels_left - 1);
         }
     }
}

Here the function calls itself again, looping through a sub-level of the array as long as there is an array to loop through and there are levels left you want to loop through.

KIKO Software
  • 15,283
  • 3
  • 18
  • 33