PHP While Loops

PHP Loop Types

Loops in PHP are used to execute the same block of code a specified number of times. PHP supports following four loop types.

 

  • for- loops through a block of code a specified number of times.
  • while - loops through a block of code if and as long as a specified condition is true.
  • do...while - loops through a block of code once, and then repeats the loop as long as a special condition is trur.
  • foreach - loops through a block of code for each element in an array.

 

We will discuss about continue and break keywords used to control the loops execution.

 

The while loop statement

The while statement will execute a block of code if and as long as a test expression is true.

If the test expression is true then the code block will be executed. After the code has executed the test expression will again be evaluated and the loop will continue until the test expression is found to be false.

Syntax:

Example

This example decrements a variable value on each iteration of the loop and the counter increments until it reaches 10 when the evaluation is false and the loop ends.

This will produce following result:

The do...while loop statement

The do...while statement will execute a block of code at least once - it then will repeat the loop as long as a condition is true.

Syntax:

Example

The following example will increment the value of i at least once, and it will continue incrementing the variable i as long as it has a value of less than 10:

This will produce following result:

<< PRIVOUS

NEXT >>

© 2015-16 All Rights Reserved Tech9schools