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.

2
  • 3
    After 1 time through the inner loop $count2 is 3, so the 2nd/3rd time through the outer loop (3 < 3) is false. If you want it to run again, you need to reset $count2.
    – Sean
    Sep 14, 2014 at 0:17
  • Of course, cheers :) Sep 14, 2014 at 0:26

3 Answers 3

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++;
}
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;
   } 
?>
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." ";
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.