PHP 5 while Loops

Loops in PHP are used to execute the same block of code a specified number of times. PHP supports following four loop types.Often when you write code, you want the same block of code to run over and over again in a row. Instead of adding several almost equal code-lines in a script,

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 true.

foreach − loops through a block of code for each element in an array.

Example -

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.

Example -

Notice that in a do while loop the condition is tested AFTER executing the statements within the loop. This means that the do while loop would execute its statements at least once, even if the condition is false the first time. The example below sets the $x variable to 6, then it runs the loop, and then the condition is checked:

Example -