Quakenet/#php Tutorial

Note: If you opened this page from an external URL pay attention that all chapters are linked together. Be sure you also read all prior chapters of this tutorial, otherwise you will miss relevant content explained before.

Loops

  1. Meaning of loops
  2. While loop
  3. Do-while loop
  4. For loop
  5. When while and when for loops?
  6. Continue and Break

1. Meaning of loops

Loops are for executing some part of code more than once. The body of the loops get executed with some different content of variables. Additional the number of iterations are controlled by an expression/condition. If the expression results to false the loop is stopped and the following php code gets execute. As an example news entries are read from a database. Such a loop prints a single news (with title, date, content,...). If there aren't any news left the loop quits and the following php code gets execute.

There are 4 types of loops, however we discuss only 3 of them. The forth type is explained in the chapter Arrays as that is a special loop for arrays. The other loops are while, do-while and for.

2. While loop

The while loop is the easiest loop type. It got a loop header with only one expression. This expression get evaluated before the next iteration and checked agains boolean. If the expression results true the loop body gets executed once. Then the next check of the expression takes place. If the expression results in false the loop is quitted and the following php code gets executed. As the expression is checked on every iteration the value must be get false at some point. If not you get an endless loop and the scripts is terminated by the webserver as the scripts runs for too long, as it cannot left the loop (default is 30 seconds).

A while loop is created with the keyword while. Then the expression to checked is followed in parentheses (()). After that a single statement or a block of statements with curly brackets is followed. As for one statements the curly brackets are not needed you should use always use curly brackets for readability.

<?php
while (CarIsDirty()) {
    
CleanTheCar();
}
?>

There is no restriction how the expression is build (with and's, or's, function calls...), however it must return a value to check.

3. Do-while loop

A do-while loop got an expression to check like the while loop. However the expression is at the end of the loop body and gets checked at this location. As the loop body is before the loop header the loop gets executed at least one time, even if the expression shows false. Thats the different to a while loop. If you need a loop which must be iterated at least one time use a do-while loop. If you need a loop which can be iterated zero times use a while loop.

A do-while loop is created with the keyword do. After that the loop body is added (again it should be always written with curly brackets). After the loop body exists the while keyword, the expression to check (in parentheses) and it MUST followed by a semicolon. At a while loop the semicolon is not followed (as wrong as in if ();) but it MUST be written if you have a do-while loop.

<?php
do {
    
connect();
    
$data getSomeData();
    
disconnect();
} while (
$data 40);
?>

4. For loop

A for loop is like a while loop with an expression to check. However it got 2 additional statements. The first one is an statement which is executed once (automatically), the second one one is executed after each iteration.

A for loop is created with the for keyword. It is followed by 3 expressions, each of them seperated by a ;. The whole list is written in parentheses. After the loop header there is the normal loop body with statements.

<?php
for (start_statementconditioniteration_statement) {
    
// statements
}
?>

At the beginning the start_statement part get executed (once). Then the condition is checked like in a while loop. After one iteration before the condition is checked again the iteration_statement part is executed.

<?php
// outputs the number from 0 to 9 (for 10 the condition is false)
for ($i=0$i<10$i++) {
    echo 
$i."\n";
}
?>

5. When while and when for loops?

As the while loop and the for loop are very similar there may be the question when to use a while and when to use a for loop. It's even possible to convert a while loop into a for loop and the other way round.

<?php
while (condition) {
   
statements;
}
// convert to for:
for (;condition;) {
   
statements;
}
?>
<?php
for (startconditer) {
    
statements;
}
// convert to while:
start;
while (
cond) {
    
statements;
    
iter;
}
?>

The number of iterations is not the reason to decide if you use a while or a for loop. However you use a for loop if you know the number of iterations. If you know it you can create at counting loop, which iterate from a value to an other value.

<?php
for ($i=0$i<10$i++) {
    
// do something with $i ($i iterates from 0 to 9)
}
?>

You use a while loop if you don't know the number of iterations (even if you can calculate the iterations somehow in your script). As an example you can read the rows out of a database, but don't know how many there are (and you actually don't care).

<?php
while (ThereAreSomeRowsLeft()) {
    
OutputTheNextRow();
}
?>

You can also read a files content which a while loop, although you can get the file size with filesize.

<?php
while (!FileEnds()) {
    
ReadOneByte();
}
?>

6. Continue and Break

The flow of a loop can also changed with other statements. You can use return to quits a loop. However, return can be use almost everywhere and has nothing to do with loops. But there exists two statements specially for loops, continue and break.

An if statement cannot be controlled this way as an if statement is not a loop. Programm code like if (...) { ..... break; .....} only works if this if statement is inside a loop and this break; actually controls the loop.

Both statements can be used with a number which indicates how many loops should be stopped/continued. The current loop is always the number 1 and is increased as much as you nested a loop inside an other loop. The statement break 1; is the same as break; (without a number).

<?php
$found 
false;
for (
$x=0$x<100$x++) {
    for (
$y=0$y<100$y++) {
        for (
$z=0$z<100$z++) {
            if (
PixelColor($x$y$z) == 0xFFCCFF) {
                
$found true;
                break 
3;
            }
        }
    }
}
?>

These nested loops get executed 100*100*100 times, that are 1 million iterations. If the execution of PixelColor(int, int, int) needs only 10 µs this code will run for 10 seconds. With break 3; we quit all 3 loops if we found the pixel we are looking for. However, if the pixel is not found we run 1 million iterations anyway.

Questions about the chapter

No questions

Back to Next to
Copyright © to the OPs of #php/QuakeNet Valid XHTML 1.0 Strict Valid CSS!