php

PHP Loops


A loop is a programming construct that allows you to repeat a set of instructions or a block of code multiple times. It's a way to automate repetitive tasks without having to write the same code over and over again until the condition is false.

PHP supports following four loop types:

  • For
  • While
  • Do-while
  • Foreach

 

1. For loop statement

It allows you to repeat a block of code for a specific number of times or for each item in a collection.

 

Syntax:

<?php
    for (initialization; condition; increment/decrement)
    {
        // code to be executed
    }
?>

 

Example: print 1 to 5

<?php
    for ($i = 1; $i <= 5; $i++) {
        echo $i . "<br>";
    }
?>

 

Output:

 

2. While Loop Statement

The while loop executes a block of code until the specified condition is true.

It is used if the number of iterations is unknown.

 

Syntax:

<?php
    while ($condition) {
        // code to be executed
    }
?>

 

Example:

<?php
    $count = 10;
    while ($count > 0) {
        echo $count . "<br>";
        $count--;
    }
?>

 

Output:

 

3. Do-While Statement

The do-while statement is executed atleast once, then will repeat the loop as long as a condition is true.

 

Syntax:

<?php
	do
	{
		// code to be executed
	} while (condition);
?>

 

Example:

<?php
	$count = 1;
	do
	{
		echo $count . "<br>";
		$count++;
	} while ($count <= 5);
?>

 

Output:

 

4. Foreach Loop

The foreach loop in PHP is used to iterate over arrays or other iterable objects. Its syntax is straightforward and simplifies the process of iteration through through the elements of an array.

 

Syntax:

<?php
	foreach ($array as $element)
	{
		// code to be executed for each $element in $array
	}
?>


Example:

<?php
    $numbers = array(1, 2, 3, 4, 5);
    foreach ($numbers as $value) 
    {
        echo $value . "<br>";
    }
?>

 

Output:

 

5. Continue/Break Statement:

Continue - The continue statement is particularly useful when you want to skip certain iterations based on a condition, allowing you to control the flow of your loop more precisely.

 

Syntax:

<?php
    while ($condition) {
        // code before continue
    
        if ($condition_to_skip) {
            continue; // skip the rest of the loop for the current iteration
        }    
        // code after continue
    }        
?>

 

Output:

 

6. Break 

The break statement is used to jump out of a loop prematurely. It is typically used within a loop (such as for, while, or do-while) to immediately terminate the loop's execution.

 

Syntax:

<?php
    while ($condition) {
        // code before break
    
        if ($condition_to_exit) {
            break; // exit the loop
        }
        // code after break
    }        
?>

 

Example:

<?php
    for ($i = 1; $i <= 5; $i++) {
        if ($i == 3) {
            // Exit the loop when $i is 3
            break;
        }
        echo $i . "<br>"; // 1 2
    }
?>

 

Output: