PHP WHILE Loop

The WHILE loop is the simplest loop in PHP.  It can be explained, basically, as “while this condition is met, do this”. PHP will continue to execute the commands in the loop so long as the condition evaluates to true.

The WHILE loop gets its roots from C, like alot of the other functions in PHP do.  Here’s how the while loop looks in C:

C Code   
  1. int x = 0;
  2. while (x < 5) {
  3. printf ("x = %d\n", x);
  4. x++;
  5. }

The same EXACT code, in PHP:

PHP Code   
  1. $x = 0;
  2. while ($x < 5) {
  3. echo "x = $x\n";
  4. $x++;
  5. }

This is pretty self explanitory.  However, it is worth mentioning that the same loop can be written another way, utilizing an endwhile statement.  See the following example:

PHP Code   
  1. $x = 0;
  2. while ($x < 5):
  3. echo "x = $x\n";
  4. $x++;
  5. endwhile;

The above example works just like the one above it, but does it without set braces.  It uses the endwhile keyword to signify the end of the while loop instead of a set brace.

In my opinion, using the first method is the way to go.  It makes the code easier to read, and less prone to errors.  Of course, this is a matter of opinion, so take it as such.  To the PHP interpreter, both formats for the WHILE statement are valid.

A note of importance.  The WHILE loop checks the condition BEFORE the loop is executed.  For example, take a look at the following code:

PHP Code   
  1. $x = 5;
  2. while ($x < 5) {
  3. echo "x = $x\n";
  4. $x++;
  5. }

In the above example, $x already has the value of 5 before the condition is checked.  The condition ($x < 5) is FALSE, so commands within the loop are never executed.

Now, if we changed the above code to say “$x = 4;” on the first line, the loop would execute one time.  $x < 5 would be true for the first loop, and the echo statement would print “x = 4″ before incrementing $x to 5.  The next iteration, $x < 5 would be false, and the while would end.

Of course, you can “hack” your way through a WHILE loop to make it function in a more custom fashion.  Take a look at this example:

PHP Code   
  1. $x=0;
  2. while (true) {
  3. echo "x = $x\n";
  4. $x++;
  5. if ($x > 4)
  6. break;
  7. }

As you can see, by setting the condition to always TRUE, the loop will execute forever.  The only way to get out of the loop is by using a break.  See the page on break for more information.

Leave a Reply

Subscribe to RSS Feed Follow me on Twitter!