Microsoft Word - Core PHP Programming Using PHP to Build Dynamic Web Sites

(singke) #1

true. The result is a loop that goes on forever. I might as well write it as while(true)
and make it very clear.


When a loop continues with no end, it's called an infinite loop. If you find your page
loading forever and ever, you may have accidentally written an infinite loop. At times,
you may intentionally create an infinite loop but stop execution somewhere in the middle
of the code block. This is accomplished with the break statement.


The break Statement


When a break statement is encountered, execution jumps outside the innermost loop or
switch statement. You've seen that this is essential to the usefulness of switch
statements. It also has some application for loops. There are cases when you need to
leave a loop block somewhere in the middle. Listing 3.6 shows this in action.


Listing 3.6 Leaving a Loop Using break


<?
while(true)
{
print("This line is printed.");
break;
print("This line will never be printed.");
}
?>


The continue Statement


The continue statement is similar to the break statement except that instead of stopping
the loop entirely, only the current execution of the loop is stopped. Control is returned to
the closing curly brace and the loop continues. Inside for loops, described below,
increments will occur just as if control had reached the end of the loop otherwise.


As you might imagine, this function is used to skip parts of a loop when a condition is
met. Listing 3.7 demonstrates this idea. Random numbers are generated inside a loop
until ten numbers, each greater than the previous, are produced. Most of the time the
body of the loop is skipped due to the if statement that triggers a continue statement.


Listing 3.7 The continue Statement

Free download pdf