Background

This is supposed to be a beginner's tutorial and while loops are not very useful to a beginner.  However, you need to know about while loops to use databases so this page is essential.  You need to have a database to make sense of while loops so work through this page and don't worry if it seems a bit pointless for now.

The while loop

Open phparrays.php and save it as phpwhile.php.  Delete all of the PHP code apart from the first three lines.  Those three lines are still putting three items of data into three locations in the array.  After those three paste this in:

while (list($arrayKey, $arrayValue)=each($george)){
    echo "<p>$arrayValue</p>";
}

Don't worry about the details of this.  Loops are structured in a very similar way to if statements:

type of loop (condition) {

    code to run goes here

}

The code inside the braces gets run more than once while the condition is met.  The above loop will echo $arrayValue until the condition becomes false (which happens when it runs out of data.  Try it and you should see three paragraphs because there are three entries in the array.  Look at the source code int he browser if you want.

The stuff inside the brackets (feel free not to read this)

You may never use either list() or each() so for now just realise that they get the data out of the array one item at a time.  In effect the array could be written like this:

while you can successfully get something from the array

echo it

The first time it tries to get an item out of the array it can so it gets the item and stores it.  As it worked the operation was a success so the echo line is run.  The server then goes back to the start of the loop to try again.  The fourth time through there is no more data so the condition fails and the looping stops.  The code inside the loop is not run as as soon as the condition fails.

As mentioned you will not be using while loops until you use databases and then the code int he condition will be different.