PHP Loop

Loop is an iterative control structure that executes the code of the same number on the same number until a certain condition is satisfied. php for loop. php foreach

Types of Loops in PHP

  • For Loop
  • While Loop
  • Do-while Loop
  • Foreach Loop

PHP for loop

This is the most commonly used loop, for loop is used when the user knows that the number of items within the block has to be executed. In this loop you initialize the variables that control the loop, write the condition and increment the variable, and all these are in one place.

Syntax

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

Example

<?php
for($a=1; $a<=5; $a++){
    echo "Value of a is: " . $a . "<br>";
}
?>

Output

Value of a is: 1
Value of a is: 2
Value of a is: 3
Value of a is: 4
Value of a is: 5

PHP while loop

While loop works when the defined condition inside the expression is true, and then it executes the conditions inside the block.

When the execution of the statement of the statement is stopped when the condition is false.

To control the loop, you give a condition that the value of that condition changes with every loop and changes are made until the condition becomes false.

If you do not increase the condition variable then the condition will never be false and the execution of the loop will last forever.

Syntax

while(condition){
// Code to be executed
}

Example

<?php
$a = 1;

while($a <= 5){
    echo "Value of a is: " . $a . "<br>";
    $a++;
}
?>

Output

Value of a is: 1 
Value of a is: 2 
Value of a is: 3 
Value of a is: 4 
Value of a is: 5

PHP do while loop

do-while loop will always execute a block of code once it executes the block of code for the first time, it will check the situation, and later, the loop is executed if the situation is true.

Do while loop statements are initially executed even if the condition is true or false. This is because condition in the do while loop is checked later.

Syntax

do{
// Code to be executed
}
while(condition);

Example

<?php
$a = 1; 

do {
    echo "Value of a is:" . $a . "<br>";
    $a++;
} while ($a <= 5);
?>

Output

Value of a is: 1 
Value of a is: 2 
Value of a is: 3 
Value of a is: 4 
Value of a is: 5

PHP foreach loop

This is a very special type loop used for the use of arrays and objects, the user can easily run the array again using the foreach loop.

Syntax

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

Example 1

<?php
$students = array("Mohan", "Rohan", "Mohit", "Rohit");
 
foreach($students as $value){
    echo "Student name is: " . $value . "<br>";
}
?>

Example 2

<?php

$arr_name = array(2,4,6,8);

foreach($arr_name as $value)
	{
	echo $value;
	}
?>

Output

Student name is: Mohan 
Student name is: Rohan 
Student name is: Mohit 
Student name is: Rohit