Saturday, August 16, 2008

PHP while loop

If you want to repeat the execution of a code block you can use loops in any programming languages. In PHP there are more ways to do it. First we will discuss the while loop, which is maybe the simplest loop type in PHP. The loops in general check their condition and depends on the result the code block will be executed 1 or more times or will not be executed at all. So the definition of the while loop is a bit similar to the definition of the if statement. It looks like this:

while (condition) statement

And a real example looks like this:

Code:

  1. while ($x < 10) $x++;

PHP F1



Of course you can use complete code blocks as well:



Code:

  1. $x = 0;

  2. while ($x < 10) {

  3. echo "$x<br/>";

  4. $x++;

  5. }

PHP F1



The while loop first checks the condition and if it is true then execute the relevant code block. After the code was executed the while loop checks the condition again and executes the code again if neccessary. This will be repeated until the condition is true. So you have to take care not to make a never ending loop like this:



Code:

  1. $x = 0;

  2. while ($x < 10) {

  3. echo "$x<br/>";

  4. }

PHP F1



In this case the x variable is never incremented so the condition will be always true. This results an endless loop.



 



Time after time it can happen that you want to break the execution of the loop indeipendent from the original condition. You can do this by using the break keyword. With break you can terminate the loop and the script will exit from the loop and continue the execution with the next statement after the loop block.



Code:

  1. $x = 0;

  2. while ($x < 10) {

  3. echo "$x<br/>";

  4. $x++;

  5. if ($x==5) break;

  6. }

  7. echo "Ready";

PHP F1



As you can see here x is smaller than 10 but the loop was ended because of break.

Beside this it can happen that you want to begin the next iteration without fully execute the actual code block. You can do this by using the continue keyword. In case of continue the actual code execution will be terminated and the loop immediately begins with a new iteration.



Code:

  1. $x = 0;

  2. while ($x < 10) {

  3. $x++;

  4. if ($x<5) continue;

  5. echo "$x<br/>";

  6. }

PHP F1

No comments: