3

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.

Rene Jorgensen
  • 169
  • 1
  • 8

3 Answers3

3

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++;
}
Charlotte Dunois
  • 4,638
  • 2
  • 20
  • 39
1

You need to reset the count2 each time you loop over count1.

Like so:

<?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 do a for loop.

for ($count1 = 0; $count1 < 3; $count1 ++) {
    echo "a".$count1."<br>";
    for ($count2 = 0; $count2 < 3; $count2 ++) {
        echo "b".$count2." ";
    }
}
worldofjr
  • 3,868
  • 8
  • 37
  • 49
JClaspill
  • 1,725
  • 19
  • 29
1

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;
   } 
?>
avanthong
  • 51
  • 3