Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 625
Rene Jorgensen Avatar asked May 23 '26 14:05

Rene Jorgensen


2 Answers

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++;
}
like image 127
Charlotte Dunois Avatar answered May 26 '26 08:05

Charlotte Dunois


You need to "reset" the value of $count2 between each time the outter loop runs. 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;
   } 
?>
like image 43
avanthong Avatar answered May 26 '26 07:05

avanthong



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!