PHP Loops

PHP Loops are used for repeating the same block of code till a specific condition reaches This saves the user time and effort by writing the code only once and by repeating it as many time as needed.

Types of PHP Loops

There are four types of loop in PHP:

Loop NameDescription
For loopIt executes a block of code a specific number of times.
For each loopIt executes a block of code for each array element.
while loopIf a particular condition is true then, it executes a block of code a specific number of times.
do…while loopDo while statement will execute code at least once, then it will repeat as long as the condition of test expression is true.

For Loop

For loop executes a block of code a specific number of times. It is used when you already know how many times the code should run.

Syntax

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

Here in above syntax three parameters are used:

  • Initialization: It initializes the loop counter value.
  • Condition: It is also known as a test counter. Each loop iteration is evaluated against this condition. The loop continues if it evaluates to TRUE. The loop finishes if it evaluates to FALSE.
  • Increment: It increments the initial counter value on each iteration.
<?php
	for($n=1;$n<=5;$n++){
		echo "Number is: ".$n."<br>";
	}
?>

Foreach Loop

Foreach loop executes a block of code for each array element.

Syntax:

Foreach($array as $value)
{
Code to be executed;
}

The value of the current element in the array is assigned to $value and the array pointer is moved by one for each loop iteration; the process is repeated until the last array element is reached.

<?php  
$lang = array("HTML", "CSS", "JavaScript", "PHP"); 

foreach ($lang as $value) {
  echo "Language: $value <br>";
}
?> 

While Loop

If a particular condition is true then, it executes a block of code a specific number of times.

Syntax

Syntax
While(condition is true)
{
Code to be executed;
}

While loop also has

  • Initialization: It initializes the loop counter value.
  • Condition: It is also known as a test counter. Each loop iteration is evaluated against this condition. The loop continues if it evaluates to TRUE. The loop finishes if it evaluates to FALSE.
  • Increment: It increments the initial counter value on each iteration.
<?php  
$n = 0;
 
while($n <= 50) {
  echo "Number: $n <br>";
  $n+=5;
} 
?>

Do While Loop

Do while statement will execute code at least once, then it will repeat as long as the condition of test expression is true.

Syntax:

do
{
Code to be executed;
}
While(condition);
<?php
	$n=1;
	do{
		echo $n."<br>";
		$n++;
	}while($n<=4);
?>

Note: In Do while the do part is executed first then the condition is checked. It means the loop is executed one time extra.

Lets see another example to get it clearly.

<?php 
$n = 5;

do {
  echo "Number is: $n <br>";//it will execute the code first and then it will check the condition
  $n++;
} while ($n <= 2);
?>