PHP Programming/The while Loop

Example 1
This is an example that prints the numbers from 0 to 4. $c starts out as 0. When the while loop is encountered, the expression $c < 5 is evaluated for truth. If it is true, it executes what is in the curly braces. The echo statement will print 0, and then add one to $c. The program will then go back to the top of the loop and check the expression again. Since it is true again, it will then return 1 and add one to $c. It will keep doing this until $c is equal to 5, where the statement $c < 5 is false. After that, it finishes.

Example 2
The first line of the program sets <tt>$myName</tt> to "Fred". After that, the while statement checks if <tt>$myName</tt> equals <tt>"Rumpelstiltskin"</tt>. The <tt>!=</tt> means 'does not equal', so the expression is true, and the while loop executes its code block. In the code block an <tt>if</tt> statement (see previous chapter) checks, if it equals Fred. Since it does, it then reassigns <tt>$myName</tt> to equal <tt>"Leslie"</tt>. Then it skips the <tt>else</tt>, since the <tt>if</tt> was true and evaluated. Then it reaches the end of the loop, so it goes back and checks if <tt>$myName</tt> does not equal <tt>"Rumpelstiltskin"</tt>. Since it still doesn't, it's true, and then it goes into the loop again. This time, the if statement is false, so the else is executed. This sets <tt>$myName</tt> to "Rumplestiltskin". We again get to the end of the loop, so it goes back, and checks. Since <tt>$myName</tt> does equal <tt>"Rumpelstiltskin"</tt>, the while condition is false, and it skips the loop and continues on, where it echos, "How did you know?"

Loops
Loops are another important basic programming technique. Loops allow programs to execute the same lines of code repeatedly, this is important for many things in programs. In PHP you often use them to layout tables in HTML and other similar functions.

Infinite Loops
Loops can be very handy, but also very dangerous! Infinite loops are loops that fail to exit, causing them to execute until the program is stopped. This is caused when no matter what occurs during the loop, the condition will never become false and therefore never exit. For example, if Example 1 subtracted 1 from <tt>$c</tt>…

$c will always be less than 5, no matter what, so the loop will continue forever. This causes problems for those of us who don't have infinite time (or computer memory!). So, in that case, let's learn a handy dandy little bugger.

If you add 'break;' to a loop, the loop will end, no matter whether the condition is false or not.

Parting example
Let's combine the two examples. Before moving on take a few moments to write out the steps this program goes through and what its output is.

For more information

 * PHP Manual: Control Structures: while.