WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

PHP 5 while Loops


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


PHP Loops

When writing code, you may want the same block of code to run over and over again. adding several almost equal code-lines in a script, we can use loops to perform a task like this.

In PHP, we have the following looping statements:

  • while - The while loop executes a block of code as long as the specified condition is true.
  • do...while - loops through a block of code once, and then repeats the loop as long as the specified condition is true
  • for - loops through a block of code a specified number of times
  • foreach - The foreach loop works only on arrays, and is used to loop through each key/value pair in an array.

The PHP while Loop

The while loop executes a block of code as long as the specified condition is true.

Syntax

while (condition is true) {
    code to be executed;
}

The example below first sets a variable $x to 2 ($x = 2). Then, the while loop will continue to run as long as $x is less than, or equal to 5 ($x <= 6). $x will increase by 2each time the loop runs ($x++):

Example

<?php
$x = 2;

while($x <=6) {
    echo "The number is: $x <br>";
    $x++;
}
?>
output//
The number is: 2
The number is: 3
The number is: 4
The number is: 5
The number is: 6

The PHP do...while Loop

The do...while loop will always execute the block of code once, check the condition, and repeat the loop as long as the specified condition is true.

Syntax

do {
    code to be executed;
} while (condition is true);

The example below first sets a variable $x to 2 ($x = 2). Then, the do while loop will write some output, and then increment the variable $x with 2. Then the condition is checked (is $x less than, or equal to 5?), and the loop will continue to run as long as $x is less than, or equal to 6:

Example

<?php
$x = 1;

do {
    echo "The number is: $x <br>";
    $x++;
} while ($x <= 5);
?>
The number is: 2
The number is: 3
The number is: 4
The number is: 5
The number is: 6

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

$i = 6; do { echo "The number is " . $i . "
"; $i++; } while($i <= 7); //Output //The number is 6 //The number is 7