Different Types of Loops in PHP

Loops are used to execute the same block of code again and again, until a certain condition is met. The basic idea behind a loop is to automate the repetitive tasks within a program to save the time and effort. PHP supports four different types of loops.

while — loops through a block of code until the condition is evaluate to true.
do…while — the block of code executed once and then condition is evaluated. If the condition is true the statement is repeated as long as the specified condition is true.
for — loops through a block of code until the counter reaches a specified number.
foreach — loops through a block of code for each element in an array.

You will also learn how to loop through the values of array using foreach() loop at the end of this chapter. The foreach() loop work specifically with arrays.

PHP while Loop

The while statement will loops through a block of code until the condition in the while statement evaluate to true.
a loop that starts with $i=1. The loop will continue to run as long as $i is less than or equal to 3. The $i will increase by 1 each time the loop runs:

    


PHP do…while Loop

The do-while loop is a variant of while loop, which evaluates the condition at the end of each loop iteration. With a do-while loop the block of code executed once, and then the condition is evaluated, if the condition is true, the statement is repeated as long as the specified condition evaluated to is true.

a loop that starts with $i=1. It will then increase $i with 1, and print the output. Then the condition is evaluated, and the loop will continue to run as long as $i is less than, or equal to 3.



PHP foreach Loop

The foreach loop is used to iterate over arrays,a loop that will print the values of the given array:

    ";

    }

    ?>