PHP Loops

You are currently viewing PHP Loops

PHP Loops

Loops are used to execute the same block of code again and again, as long as a certain condition is true.
In PHP, we have the following loop types:

  •  while – loops through a block of code as long as the specified condition is true.
  • do…while – loops through a block of code once, and then repeats the loop as long as the specified condition is true.
  • for – loops through a block of code a specified number of times.
  • foreach – loops through a block of code for each element in an array.
  1. while loop: This loop executes a block of code as long as the specified condition is true. The syntax for the while loop is as follows:

while (condition) {
code to be executed;
}

The example below displays the numbers from 1 to 5 using while loop:

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

				
			
				
					Output:-
The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5

				
			

2. do…while loop: This loop executes a block of code once, and then repeats the loop as long as the specified condition is true. The syntax for the do…while loop is as follows:

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

Example of do..while loop-:

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

				
			
				
					Output:-
The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5

				
			

3. for loop: This type of loops is used when the user knows in advance, how many times the block needs to execute. The syntax for the for loop is as follows:

for (init counter; test counter; increment counter) {
code to be executed for each iteration;
}

Parameters:
init counter: Initialize the loop counter value

  • test counter: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it evaluates to FALSE, the loop ends.
  • increment counter: Increases the loop counter value

Example of for loop-:

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

				
			
				
					Output:-
The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5

				
			

4. foreach loop: This loop is used to iterate over arrays. The syntax for the foreach loop is as follows:

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

Here’s an example of a foreach loop that prints each element in an array:

				
					<?php  
$colors = array("red", "green", "blue", "yellow"); 
foreach ($colors as $value) {
  echo "$value <br>";
}
?>

				
			
				
					Output-:
red
green
blue
yellow

				
			

Leave a Reply