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.
source to share
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." ";
}
}
source to share