Search code examples
phpwhile-loopnested-loops

while loop inside another while loop only runs one time


Hi I'm fairly new to coding and brand new to the stackoverflow community, so bear with me.

I'm trying to make a code that will create the following output:

a0

b0 b1 b2 a1

b0 b1 b2 a2

b0 b1 b2

with this code:

    <?php
    $count1 = 0;
    $count2 = 0;
    while ($count1 < 3){
       echo "a".$count1."<br>";
       while ($count2 < 3){
          echo "b".$count2." ";
          $count2 ++;
          }
       $count1++;
       } 
    ?>

My problem is that the nested while loop only runs one time and gives me:

a0

b0 b1 b2 a1

a2

The output I want might be achieved by using a for loop or some other method instead, but I'm curious why this doesn't work. It's also an early stage of a code that should run through a database query for which I have only seen examples with while loops.

Thanks it advance.


Solution

  • You need to reset the counter. You don't need to define the variable outside of the whiles, just do it in the first one.

    $count1 = 0;
    while ($count1 < 3){
        echo "a".$count1."<br>";
        $count2 = 0;
        while ($count2 < 3){
            echo "b".$count2." ";
            $count2 ++;
        }
        $count1++;
    }