This loop can be used to repeat a code several times untill the condition of the loop is not true anymore. The strucuture of a while loop looks like this:
while( ... condition ... )
... act code ...
}
So, while the condition between brackets is still true, it will keep repeating the ‘act code’ (you can put any valid php code there). Each time it has executed the ‘act code’ , it will go back to the first line of the loop and check whether the condition is still true. If this is the case, it will repeat the code, if not: the loop will stop (break) and the script will continue with the next following code, skipping the loop code this time. A simple example:
<?php
$start = 0;
$end = 10;
$counter = $start;
while($counter <= $end) {
echo "counter: ".$counter;
$counter++;
}
?>
This code sets a variable $counter equal to a start value ( 0 ) and then executes a loop which is repeated as long as the value of the counter is less than the end value ( set in variable $end = 10 ). Then it shows the current value of the counter and increases the counter value by one. It repeats the while loop as long as the $counter value is still smaller than or equal to the $end value. The result of this while loop would be:
counter: 0
counter: 1
counter: 2
counter: 3
counter: 4
counter: 5
counter: 6
counter: 8
counter: 9
counter: 10
It counts to 10!
Another good use of the while loop is for getting all results from the database. I won’t go in detail here as MySql queries aren’t discussed yet. But in that case the condition puts the first result it finds from a query, into a variable. Then it will execute the ‘act code’ and then check the condition again: it will check if there are any more results from the database, if so , it will put the next found result in the variable and execute the ‘act code’ again but then with that new found result as value of the variable, etc..
The code looks like this (just an example) :
while ( $result = msql_fetch_assoc($query) ) {
//while there are still results to be handled from the query
echo $result['message']; //for example: show the value of the field 'message' from this result
}
This can be used to (for example) show all messages for forums, guestbooks, etc..
Now we’ve come to the end of this chapter. In the next chapter we’ll be discussing the for loop, which can as well be used instead of the while loop in several cases.
Admin.


Fri, Jan 15, 2010
PHP & MySql