Membership
Main Menu
Forum Boards
Stats
- 20 tutorials
- 74,814 members
- 734,896 forum posts
- 13 blog posts
Tutorials
PHP Loops
Views: 25162
The While Loop
The basic While loop syntax looks like this:
initialization
while (condition) {
instruction
iteration
}
A working example might look like this:
In essence, this while loop is exactly like a for loop. It has a set initializer, a set condition, and a set iteration. You are, of course, free to switch the order of the instruction and the iteration. In this example, it would actually be better to write this as a for loop, because that's what the for loop was made for.
The power of a while loop is being able to combine the initializer and even sometimes the iteration with the condition. One scenario in which this comes in handy is if you have a list of information in a database and you want to grab that information and make a loop to display that data, but you aren't sure how many iterations there will be, because you aren't sure how many rows will be returned from the database.
Example:
In this example, we run a query to select all the names in a table in your database. Inside the ( ...), all 3 components (initialization, condition, iteration) are combined into a single expression.
The initialization is easy enough to spot: $name = ... is the initialization.
mysql_fetch_assoc is a special function that grabs a name from the result source of the query and then internally increments the pointer of that result source to the next name in the results. This is the iteration, because when the loop finishes and goes back to the beginning, it will have a new name to fetch.
The condition comes into play by the act of being able to initialize $name to the next name in the result source. If mysql_fetch_assoc gets to the end of the list of names, it will return false, so the next time the loop tries to assign a name to $name, it will fail, thus ending the loop.
