WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

PHP 5 while Loops



Loop through the code block a specified number of times, or loop through the code block when the specified condition is true.


PHP loop

When you write code, you often need to run the same block of code over and over again. We can use loop statements in our code to accomplish this task.

In PHP, the following loop statements are provided:

  • while -Loop through code blocks as long as the specified conditions are true
  • do ... while -First execute the code block once, then repeat this loop when the specified conditions are met
  • for -loop through the specified number of times of the code block
  • foreach -loop through code blocks based on each element in the array

while loop

The while loop will execute the code block repeatedly until the specified condition is not met.

Syntax

  while     (condition)  
  { 
       Code to execute;  
 }  

Example

The following example first sets the variable i to 1 ($ i = 1;).

The while loop will then continue to run as long as i is less than or equal to 5. Each time the loop runs, i is incremented by 1:

<html>
<body>

<?php
$i=1;
while($i<=5)
{
    echo "The number is " . $i . "<br>";
    $i++;
}
?>

</body>
</html>

Output:

The number is 1
The number is 2
The number is 3
The number is 4
The number is 5

do ... while statement

The

do ... while statement executes the code at least once, then checks the condition, and repeats the loop as long as the condition is true.

Syntax

  do  
  { 
       Code to execute;  
 }  
  while     (condition);  

Example

The following example first sets the variable i to 1 ($ i = 1;).

Then start the do ... while loop. The loop increments the value of the variable i by 1 and outputs it. First check the condition ( i is less than or equal to 5), as long as i is less than or equal to 5, the loop will continue to run:

<html>
<body>

<?php
$i=1;
do
{
    $i++;
    echo "The number is " . $i . "<br>";
}
while ($i<=5);
?>

</body>
</html>

Output:

The number is 2
The number is 3
The number is 4
The number is 5
The number is 6

for loops and foreach loops are explained in the next chapter.