While loop inside another while loop only runs once

Hi I am fairly new to coding and completely new to the stackoverflow community, so bear with me.

I am trying to create some code that will generate 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 once and gives me:

a0

b0 b1 b2 a1

a2

The result I want can be achieved with a for loop or some other method, but I am curious as to why that doesn't work. This is also an early step in code that needs to be executed through a database query, for which I've only seen examples with while loops.

Thanks for this.

+3


source to share


3 answers


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



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

      

+3


source


You need to reset count2

every time you go through count1

.

Same:

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

      



You can also loop for

.

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

      

+1


source


You need to "reset" the value of $ count2 between each start of the wait loop. Note the $ count2 = 0:

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

      

+1


source







All Articles