The PHP While Statement
There will be many times when you want your PHP program to perform a task repeatedly until you tell it to stop. For example, you could design your program to count from 1 to 10 in increments of one. The program will start with 1 and then count 2, 3, 4, 5, 6, 7, 8, 9, 10 and stop. You will use a PHP loop statement to do this. In this tutorial we will discuss one type of loop statement called the PHP while statement. You guessed it. The while statement will instruct your program to do a task repeatedly "while" you want it to do so. Let's take a look at the basic format of the while statement. Before we actually begin the while statement we must first initialize the variable that we will be using in the test expression. We need to give this test variable a beginning value. Let's set the initial value of our test variable $number to 1.
Now we are ready to write the while statement.
This is the controlling code of the while statement. It says "Execute the code that is between the { and } while the expression remains true. In the example the loop of code will be executed continuously as long as $number is less than 11. The value of $number has been set to 1 before the while statement began. So the statement will be repeated 10 times.
This is the code that will be executed repeatedly. It will first print the current value of $number and the HTML <br> code to the web browser and then it will increment the value of $number by 1. The second line of code is necessary because it increases the value of the variable each time the loop is executed. If this code was omitted, the value of the $number variable would not be changed and the loop would be executed indefinitely. You can see why the code that changes the value of $number is so important. It will stop the loop when the value of $number is 11 (which is not less than 11). The result will look like this in the browser. 1 2 3 4 5 6 7 8 9 10 | |||||
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.