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:
while ($x < 10) $x++;
Of course you can use complete code blocks as well:
Code:
$x = 0;
while ($x < 10) {
echo "$x<br/>";
$x++;
}
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:
$x = 0;
while ($x < 10) {
echo "$x<br/>";
}
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:
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:
$x = 0;
while ($x < 10) {
$x++;
if ($x<5) continue;
echo "$x<br/>";
}
No comments:
Post a Comment