Control Structures and While Loops
By Darren W. Hedlund2005-06-20
Control structures and while loops
The "while" loop works on a very simple concept: while something evaluates to true, keep doing something else. Because we're working on the basis of true and false, we will need our comparison operators (discussed in lesson 7). If you can't quite remember, comparison operators compare values (or types) in two (or more) variables and return either "true" or "false".
Let's begin by looking at the syntax of the "while" loop:
while ( expression is true ) { do something }
the EASIEST way to show how the "while" loop works is to show you code right from the PHP documentation:
|
This is by far the greatest example code for the "while" loop because it shows you the very essence of why it exists. What we do first is declare a variable $i and give it an initial value of "1". The next few lines say exactly this: "while the variable $i is less than or equal to 10, print the variable then add 1 to it".
And here is what PHP will do (pardon the very detailed explanation, but it's important):
-set $i to 1
-begin loop, $i is less than or equal to 10 (true), so do everything inside the block
-print $i (1)
-increase $i by 1 (now $i is 2)
-continue loop, $i is less than or equal to 10 (true), so do everything inside the block
-print $i (2)
-increase $i by 1 (now $i is 3)
-continue loop, $i is less than or equal to 10 (true), so do everything inside the block
-print $i (3)
-increase $i by 1 (now $i is 4)
-continue loop, $i is less than or equal to 10 (true), so do everything inside the block
-print $i (4)
-increase $i by 1 (now $i is 5)
-continue loop, $i is less than or equal to 10 (true), so do everything inside the block
-print $i (5)
-increase $i by 1 (now $i is 6)
-stop loop, $i is now greater than 5 (false), don't do anything inside the block and move on
Here is the output you will see:
"1
2
3
4
5"
You have to be VERY careful with the "while" loop because you may accidentally throw your program into an infinite loop by writing and expression that always yields a true answer. PHP itself by default is set to stop a process which spans more than 30 seconds but if you accidentally get into an infinite loop on your web server, you will have some explaining to do to your administrator. Here is an example (although very stupid) of code which will yield an infinite loop:
|
This will print as many numbers (starting from 1) as it can before PHP decides to shut down the program by force.
To sum up the "while" loop: the "while" loop allows you to keep executing a chunk of code as long as some expression is true.
Tutorial pages:
|
|
|||||||||
You might also want to check these out:
|
Leave a Comment on "Control Structures and While Loops"
You must be logged in to post a comment.
Link to This Tutorial Page!

