- Instant help with your Php coding problems

PHP while loop

If you want to repeat the execution of a code block you can use loops in any programming language. 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 depend 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:

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

Of course, you can use complete code blocks as well:

$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 necessary. This will be repeated until the condition is true. So you have to take care not to make a never-ending loop like this:

$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 in an endless loop.

Break and continue in the while loop

Time after time it can happen that you want to break the execution of the loop independent 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.

$x = 0;
 
while ($x < 10) {
   echo "$x<br/>";
   $x++;
   if ($x==5) break;
}
 
echo "Ready";

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

Besides 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 the case of continue the actual code execution will be terminated and the loop immediately begins with a new iteration.

$x = 0;
 
while ($x < 10) {
   $x++;
   if ($x<5) continue;
   echo "$x<br/>";
}

 

Share "PHP while loop" with your friends