g
Printer Friendly Version

editor  
BellaOnline's PHP Editor
 

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.

$number = 1;

Now we are ready to write the while statement.

while (expression)
{ do this }
while ($number < 11)
{ echo "$number <br>";
$number++;
}


while ($number < 11)
while (expression)
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.

{ echo "$number <br>";
$number++;
}
{ do this }
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!

PHP Site @ BellaOnline
View This Article in Regular Layout

Content copyright © 2013 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 Editor Wanted for details.



| About BellaOnline | Privacy Policy | Advertising | Become an Editor |
Website copyright © 2023 Minerva WebWorks LLC. All rights reserved.


BellaOnline Editor