PHP Loops

Loops are used to execute a block of statements, multiple times until and unless a specific condition is fulfilled. The basic idea behind a loop to helps the user to save both time and effort of repetitive tasks multiple times.
PHP supports four different types of loops.

  • for loop
  • foreach loop
  • while loop
  • do-while loop



1. The PHP for Loop

The for loop is used when user knows in advance how many times the block of code should run.

Syntax:

for (initialization expression; test condition; update expression) {
// code to be executed
}

In PHP for loop, a loop variable is used to control the loop. First, initialize this loop variable to some value, then check whether this variable is less than or greater than the counter value.

If statement is true, then loop body is executed and loop variable gets updated . Steps are repeated till exit condition comes.

  • Initialization Expression: In this expression we have to initialize the loop counter to some value. for example: $num = 0;
  • Test Expression: In this expression we have to test the condition. If the condition evaluates to true then we will execute the body of loop and go to update expression otherwise we will exit from the for loop. For example: $num <= 7;
  • Update Expression: After executing loop body this expression increments/decrements the loop variable by some value. for example: $num += 1;

Example#1

<?php  
  
// code to illustrate for loop 
for ($x = 0; $x <= 7; $x++) { 
    echo "The number is: $x <br>"; 
}  
  
?> 

Output:

The number is: 0
The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5
The number is: 6
The number is: 7


Example#2

<?php  
  
// code to illustrate for loop 
for ($x = 1; ; $x++) {
    if ($x > 7) {
        break;
    }
   echo "The number is: $x <br>"; 
}
  
?> 


Example#3

<?php  
  
$x = 1;
for (; ; ) {
    if ($x > 10) {
        break;
    }
   echo "The number is: $x <br>"; 
    $x++;
}
  
?> 




2. PHP foreach Loop

The PHP foreach Loop construct provides an easy way to iterate over arrays. foreach works only on arrays and objects and will create an error when you try to use it on a variable with a different data type.

Syntax:

foreach($array as $value){
// Code to be executed
}


Example#1

<?php
$colors = array("red", "green", "blue", "yellow");

foreach ($colors as $value) {
    echo "$value <br>";
}
?>

Output:

red
green
blue
yellow




The PHP while Loop

The while loop is very simple loop in PHP. The while loop executes a block of code as long as the specified condition is true.

Syntax:

while (condition is true) {
code to be executed;
}


Example

<?php
$x = 1;

while($x <= 4) {
    echo "The number is: $x <br>";
    $x++;
}
?>

Output:

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


Pin It on Pinterest

Shares
Share This