Tutorials

PHP Loops

by Crayon Violent on Jun 19, 2008 2:46:30 PM

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.

Comments

Again, very nice CV. Only thing i would mention is that it's not strictly true that a for loop requires all 3 parameters. This is a perfectly valid for loop:

As is this:

Of course, they serve no real useful purprose (use a while loop, it's easier to follow) but i had to find something wrong with it :P

1. Ben Smithers on Jun 20, 2008 5:07:40 AM

Ah you are right, but in order for the loops to function properly, they still need to have all the components somewhere. Your first example, while syntactically correct, would in and of itself be an infinite loop. Using your first example, you would have to put the condition and iteration inside the instruction. Example:

I'm glad you pointed that out though : )

2. Crayon Violent on Jun 20, 2008 10:19:46 AM

A concise explanation of loops. Very good.

3. kahratka on Jun 20, 2008 10:32:40 AM
Login or register to post a comment.