pileup
pileup

Reputation: 3262

foreach loops with dynamic number of loops

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. . .
}

Upvotes: -1

Views: 72

Answers (1)

KIKO Software
KIKO Software

Reputation: 16688

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.

Upvotes: 2

Related Questions