Loops in PHP

Loops are the blocks used for executing the same code repeatedly.  There are following loops in PHP.

  • for Loop
  • while Loop
  • do-while Loop
  • foreach Loop

 

for Loop:

for Loop in PHP execute the same code specified in its parameter.

Example:

 

 

Output:

0
1
2
3
4

Explanation: In above example, we initialize the variable $i value=0 and we also specified that this value of $i will be increment only 5 times. So the following line was executed 5 times.

echo $i.'<br/>’;

while Loop:

The while loop in PHP will execute the PHP script unless the text expression goes false.

Example:

 

 

Output:

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

Do-while Loop in PHP

 

The do-while loop always executes the code once and check the condition, whether it’s true or false and repeat the block of code if the condition goes true.

 

 

For each loop

 

The foreach loop works only on arrays and at the time of iteration, foreach loop assigns the value of array to a new variable.

 

red
green
blue
yellow