Php Looping Statement


Looping statements in PHP are used to execute the same block of code a specified number of times. very often when you write code, you want the same block of code to run a number of times. you can use looping statements in your code to perform this. In PHP we have the following looping statements.

  • The while statement
  • The do...while statement
  • The for statement
  • The foreach statement

The while statement

The while loop is an entry control loop that will check the first condition after that condition is true then execute the statement.

Syntax

while(condition){
//code to be executed;
}
 

Example

The following example demonstrates a loop that will continue to run as long as the variable $i is less than one equal to 5. The $i variable will increase by 1 each time the loop runs.

<?php
$i = 1;
while($i <= 5) {
    echo "The number is: $i <br>";
    $i++;
}
?>

The do...while statement

The do...while statement is an exit control loop that will first execute a statement after check condition is called an exit control loop.

Syntax

do{
code to be executed;
}
while(condition);

Example

The following example will increment the value of $i at least once, and it will continue incrementing the variable $i as long as it has a value of less than 5.

<?php
$i=0;
do{
 $i++;
 echo "The number is ".$i."</br/>";
}
while($<5);
?>

The for statement

The for statement is an entry loop control loop. it is used when knowing many times you want to execute a statement.

Syntax

for(initialization;condition;increment){
code to be executed;
}

Example

The following example prints the text "Hello World!" five times.

<?php
for ($i = 0; $i <= 5; $i++) {
    echo "The number is: $i <br>";
}
?>

The foreach statement

The foreach statement is used to loop through arrays. For every loop, the value of the current array element is assigned to $value (and the array pointer is moved by one) so on the next loop, you will be looking at the next element.

Syntax

foreach(array as value){
 code to be executed;
}
 

Example

The following example demonstrates a loop that will print the values of the given array.

<?php
$arr= array("one", "two", "three");
foreach ($arr $value) {
  echo "Value: ".$value."<br/>";
}
?>