PHP while loop


Home - Tutorials - Basics

In this tutorial I will show you how with code examples to use while loops in PHP.

Tutorial info:


Name:PHP while loop
Total steps:2
Category:Basics
Level:Beginner

Bookmark PHP while loop



Bookmark and Share

Step 1 - The while loop


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++;
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. }
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. }
In this case the x variable is never incremented so the condition will be always true. This results an endless loop.





Next Step of PHP while loop


Tags: php while loop, while loop, php while, php, while, loop



Follow phpf1 on Twitter




F1 Site Family
AJAX F1
HTML F1
Java F1
JavaScript F1
PHP F1

Total time: 0.0203