Home Logo
Show Full Menu
Hide Full Menu
 

For Loop

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


In this tutorial we will learn the For Loop
Note: Before you begin this tutorial, please make sure you understand the While Loop tutorial.

In this tutorial we are going to look at the for loop. The for loop is a loop that repeats until a certain condition is no longer met which then the rest of the PHP is executed, exactly the same as the while loop except it is much tidier.
The for loop allows you to create the counter and the increment into the condition section instead of having to create them separately.

The condition section works like this,
    Script
  • for(counter; condition to be checked; instrumentation){
  • Task if condition is true
  • }


To write a for loop
    Script
  1. <?php
  2. for($num = 0; $num < 10; $num++){
  3. print "The number now is $num <br/>";
  4. }
  5. ?>
So the end result is exactly the same as the while loop however this time it is much tidier.
    Result
  • 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 for 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.
    Result
  • for($num = 0; $num >=0; $num++){
  • print $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