The PHP Break Statement
The PHP break statement is placed within the code of a loop statement to cause your program to break out of the loop statement. In the past few tutorials we discussed several types of loop statements. Each of these loop statements already had a test expression that controlled when to stop the loop. So why would you want to add another "stop" code? There are numerous reasons for doing this. For example you would use the break statement to prevent your program from performing unwanted actions such as dividing by zero. Below is an example of a break statement that has been added to a loop statement. You will recognize this loop statement from the previous tutorial about the PHP for statement. If it has been some time since you have read that tutorial, go back and refresh your memory.
This is the same as in the previous tutorial. The for statement begins with the word for and has the three expressions between the parenthesis.
The first NEW thing you see here is an if statement. This is our second test expression. It controls the break statement that follows it. In our example we want to stop the loop if the value of the $number variable is 5. When this condition is true the following is executed --> { break; }. The program will not continue through the rest of the statement --> else { do this }. It will "break out" of the loop. When the if statement test is false, the following is ignored --> { break; }. And the else clause will be executed --> else { do this }.
This is the else clause that will be executed when the if statement is false. As in the previous tutorial, the { do this } instructions are to print the current value of the $number variable and the HTML <br> code to the web browser.
Here is what will appear in the web browser. 1 2 3 4 | |||||||
This site needs an editor - click to learn more!
Editor's Picks Articles
Top Ten Articles
Previous Features
Site Map
Content copyright © 2023 by Diane Cipollo. All rights reserved.
This content was written by Diane Cipollo. If you wish to use this content in any manner, you need written permission. Contact
BellaOnline Administration
for details.