Home Logo
Show Full Menu
Hide Full Menu

While Loop

Created: 11/10/10 Views: 2418 myFave Image

In this tutorial we will learn the While Loop
In PHP there are what is called loops. The idea of a loop if for this particular script to loop (repeat) until a certain condition is met.

In this tutorial we are going to look at the while loop. The while loop is a loop that repeats until a certain condition is no longer met which then the rest of the PHP is executed.
The best way to understand this is to see it in examples.

To write a while loop
  1. <?php

  2. $num = 0;

  3. while($num < 10){
  4. print "The number now is $num <br/>";
  5. $num++;
  6. }

  7. ?>
So what is going on?
As you can see we've created a variable called 'num' and the value of that is zero (L3).
We have then written a while loop (L5,L6,L7,L8), it starts with the word while, two brackets and two curly brackets.
What ever is in the brackets is the condition for the while loop (L5), which is, whilst the variable 'num' is smaller than 10.
Now we create the tasks for it to perform inside the curly brackets (L6,L7), which is, print the sentence with the current value of the variable 'num' and add 1 to the variable 'num' ($num++ is the same as $num + 1).

So what will happen?
This will print "The number now is" followed by the value of 'num' and then with a break (<br />) until the value of 'num' reaches 10 where is will stop.
  • The number now is 0
  • The number now is 1
  • The number now is 2
  • The number now is 3
  • The number now is 4
  • The number now is 5
  • The number now is 6
  • The number now is 7
  • The number now is 8
  • The number now is 9

Give it a go yourself!

Warning: With a while loop, it is possible to create a loop that is never ending, if you happen to create such a loop and run it, you will have errors and your browsers is likely to freeze before quitting.
This is an example of a never ending loop.
  • $num = 0;

  • while($num >=0){
  • print $num;
  • $num++;
  • }
This loop will never end as each time it's processed, 'num' has 1 added to it and so it will always be greater or equal to zero.
It is easy to create an endless loop by accident, if you use the first example and never include $num++ then the value of num would never increase and will stay at 0 and so it will always be smaller than 10.

back to: PHP Extended

There are no comments