PHP Loops: for, foreach, while, do…while

In PHP loops, are used to execute the certain portion of the code number of times until certain condition are met.

The types of loops are:

  • for
  • for…each
  • while
  • do…while

For Loop

  • In PHP, for loop is used to perform some tasks repeatedly for a specific number of times.
  • For loop is used, when you know in advance, how many times to repeat the task.

Syntax:-

<?php
	for(initialization; condition; increment/decrement counter){
		//block of code that is executed repeatedly
	}
?>

Flowchart:-

For loop

Example:-

<?php
	for($i=25; $i<=35; $i++){
		echo "$i <br/>";
	}
?>

Output:-

25
26
27
28
29
30
31
32
33
34

35

For each Loop

  • In PHP, for each loop is used to loop over all the elements of an array.
  • For each loop is used, if you want to perform some task repeatedly for each element of an array.
  • Starting from first element of array, it iterates through each element in the array

Syntax:-

<?php
	foreach($arrayname as $value){
		//block of code that is executed repeatedly
	}
?

OR

<?php
	for each($arrayname as $key = $value){
		//block of code that is executed repeatedly
	}
?>

Flowchart:-

ForEach Flow Chart

Example:-

Here we create array with five elements and print that array.

<?php
	$number = array(50,60,70,80,90);
	foreach($number as $value){
		echo $value. "<br/>";
 	}
?>

Output:-

50
60
70
80
90

While Loop

  • In PHP, while loop is used to repeatedly perform some task until condition within while loop is satisfied.
  • While loop will execute the code if and only if a specified condition is true otherwise it will be terminated.

Syntax:

<?php
	Initialization;
	while(condition){
		//block of code 
		Increment/decrement counter;
	}
?>

Flowchart:-

While loop flow chart

Example:-

Here we print 25 to 30 numbers using while loop.

<?php
	$number = 25;
	while($number <= 30){
		echo "$number <br/>";
		$number++;
 	}
?>

Output:-

25
26
27
28
29
30

Do…While Loop

  • In PHP, do…while loop is used to repeatedly perform some task until condition within do…while loop is satisfied.
  • In do…while loop, even if the condition is false, the block of code will be executed at least one time.

Syntax:-

<?php
	Initialization;
	do{
		//block of code 
		Increment/decrement counter;
	}
	while(condition);
?>

Flowchart

do while loop

Example:-

Here we print 25 to 30 numbers using do…while loop.

<?php
	$number = 25;
	do{
		echo "$number <br/>";
		$number++;
 	}
	while($number <= 30)
?>

Output:-

25
26
27
28
29
30