Been trying to figure this one out for the last 3 hours and so hard to find any search results for "nesting for loop inside for loop", so I must ask this question and somebody can help clarify, as much of an amateur question this is, will much appreciate any and all help.
So I have this block of code underneath, for a beginners looping exercise I found at http://www.w3resource.com/php-exercises/php-for-loop-exercises.php on question 3 of that page. The end result should be on that page as well.
<?php
for($a = 1; $a <= 5; $a++) {
for($b = 1; $b <= $a; $b++) {
echo "*";
if($b < $a) {
echo " ";
}
}
echo "<br />";
}
?>
It turns out like a triangle shape made up of 15 little *
I am trying to figure out exactly how this works, as even though the site has an answer, I want to understand so I can write things myself instead of copy pasting.
Below is what I have been able to make out after reading php.net and also trying to look for a solution on Google.
So, the $a for loop starts off as true so loop continues onto the $b FOR loop, it is true so it will echo *, At this point $b is not < $a as loop is not yet over so the ++ have not been added yet and if statement is false, so we <br /> and re-run loop.
Second time around. Now $a=2 and for loop is still true so it will go on to $b for loop and echo *. This is where I get confused. The $b has ++ at the end of its statement, so doesn't it mean that after loop 1 $b = 2 and if is still false ?
In my head I keep thinking it should print out like:
<br />* <br /> * <br />
instead of this:
<br />* <br /> * * <br />
My conclusion.
- The
$bvalue will reset back to 1 after each loop and repeats itself untilifstatement is false.
OR
- The
*that get printed are stored and will be the automatic starting point at the beginning of each loop. I understand that if doing a simple print for afor($i=0;$i<11;$i++)loop will carry the value over, however in my situation, a printed*is not a value, so it shouldn't be carried over to a new loop.
OR
- I am just completely off with both my conclusions.
Either way, its been confusing me so badly.
Sorry for long explanation.
Thanks.