In this tutorial you will learn about the PHP Looping & Iteration and its application with practical example.
Looping & Iteration statements are used to execute the block of code repeatedly for a specified number of times or until it meets a specified condition. PHP supports four loop types.
The for loop in PHP
The for loop is used when we want to execute block of code known times.
1 2 3 4 |
for (initialization; condition; increment) { //Block of code to be executed; } |
Property | Description |
---|---|
initialization | Sets a counter variable |
condition | It test the each loop iteration for a condition. If it returns TRUE, the loop continues. If it returns FALSE, the loop ends. |
increment | Increment counter variable |
The while loop in PHP
The while loop will execute a block of statement as long as a test expression is true.
1 2 3 4 |
while (condition) { //Block of code to be executed comes here; } |
The do…while loop in PHP
The do…while statement will execute a block of code and then test the condition for next iteration and executes next only if condition is true, block of code executes at least once.
1 2 3 4 |
do { //Block of code to be executed comes here; }while (condition); |
The foreach Loop in PHP
The foreach statement is used to iterate over all elements of an array. It executes same piece of code for every element of an array
1 2 3 4 |
foreach ($array as $value) { //Block of code to be executed comes here; } |