Saturday, March 20, 2010

PHP Looping - While Loops

---------------------------------------------------------------------------------------------------------------------------------------
Execute a block of code a specified number of times, or while a specified condition is true.
---------------------------------------------------------------------------------------------------------------------------------------

In PHP, we have the following looping statements:
  • while - loops through a block of code while a specified condition is TRUE.
  • do...while - loops through a block of code once, and then repeats the loop as long as a specified condition is TRUE.
  • for - loops through a block of code a specified number of times.
  • foreach - loops through a block of code for each element in an array.


While Loop

The following example defines a loop that starts with x=1. The loop will continue to run as long as x is less than, or equal to 3. x will increase by 1 each time the loop runs:


#####################
The Output:

The number is 1
The number is 2
The number is 3
#####################


do...while Statement

The following example defines a loop that starts with x=1. It will then increment x with 1, and write some output. Then the condition is checked, and the loop will continue to run as long as x is less than, or equal to 3:


#####################
The Output:

The number is 2
The number is 3
#####################

0 comments:

Post a Comment