Loops through a block of code a specified number of times, or when a specified condition is true.
When you write code, you often need to have the same blocks of code run 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 - loops through a block of code as long as the specified condition is true
do...while - first executes a block of code once, then repeats the loop if the specified condition is true
for - Loops through a block of code a specified number of times
foreach - Loop through a block of code based on each element in an array
A while loop will execute a block of code repeatedly until a specified condition is not true.
while (condition){code to be executed;}
The following example first sets the value of variable i to 1 ($i=1;).
Then, the while loop will 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 1The number is 2The number is 3The number is 4The number is 5
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.
do{Code to be executed;}while (condition);
The following example first sets the value of variable i to 1 ($i=1;).
Then, start the do...while loop. The loop increments the value of variable i by 1 and then 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 2The number is 3The number is 4The number is 5The number is 6
The for loop and foreach loop will be explained in the next chapter.