Quick Contact

    Looping (Iteration)

    When you write code, you want the same block of code to run over and over again in a row. Instead of adding several almost equal code-lines in a script, we can use loops to perform a task like this. A Loop is an Iterative Control Structure that involves executing the same number of code a number of times until a certain condition is met. The basic idea behind a loop is to automate the repetitive tasks within a program to save the time and effort.

    Loops in PHP are used to execute the same block of code a specified number of times.

    In programming it is often necessary to repeat the same block of code a given number of times, or until a certain condition is met. This can be accomplished using looping statements.

    PHP supports following four loop types.
    • For: loops through a block of code a specified number of times.
    • While: loops through a block of code if and as long as a specified condition is true.
    • do…while: loops through a block of code once, and then repeats the loop as long as a special condition is true.
    • foreach: loops through a block of code for each element in an array.
    For Loop

    The for loop repeats a block of code until a certain condition is met. It is typically used to execute a block of code for certain number of times.

    The flowchart shown below illustrates how for loop in php works:

    loop in php

    The For-statement loop is used when you know how many times you want to execute a statement or a list of statements. For this reason, the For loop is known as a definite loop. The syntax of For loops is a bit more complex, though for loops are often more convenient than While loops.

    The For-loop syntax is as follows:
    for(initialization; condition; increment){
        // Code to be executed
    }
    
    The parameters of for loop have following meanings:
    • initialization: it is used to initialize the counter variables and evaluated once unconditionally before the first execution of the body of the loop.
    • Condition: in the beginning of each iteration, condition is evaluated. If it evaluates to true, the loop continues and the nested statements are executed. If it evaluates to false, the execution of the loop ends.
    • Increment: it updates the loop counter with a new value. It is evaluate at the end of each iteration.
    Let’s Understand by using following Program

    The example below defines a loop that starts with $i=1. The loop will continue until $i is less than, or equal to 5. The variable $i will increase by 1 each time the loop runs:

    <html lang="en">
    <head>
        <title>PHP for Loop</title>
    </head>
    <body>
        <?php
            for($i=1; $i<=3; $i++){
                echo "The number is " . $i . "<br>";
            }
        ?>
    </body>
    </html>                                
    
    Output of this code:

    The number is 1
    The number is 2
    The number is 3

    The code below uses the for loop to print values of multiplying 10 by 0 through to 10:

    <?php
        for ($i = 0; $i < 10; $i++){
            $product = 10 * $i;
            echo "The product of 10 * $i is $product <br/>";
        }
    ?>
    
    Output of this code:

    The product of 10 x 0 is 0
    The product of 10 x 1 is 10
    The product of 10 x 2 is 20
    The product of 10 x 3 is 30
    The product of 10 x 4 is 40
    The product of 10 x 5 is 50
    The product of 10 x 6 is 60
    The product of 10 x 7 is 70
    The product of 10 x 8 is 80
    The product of 10 x 9 is 90

    The following example makes five iterations and changes the assigned value of two variables on each pass of the loop:

    <html>
    <body>
        <?php
            $a = 0;
            $b = 0;
            for( $i = 0; $i<5; $i++ ) {
                $a += 10;
                $b += 5;
            }
                echo ("At the end of the loop a = $a and b = $b" );
        ?>
    </body>
    </html>
    
    This will produce the following result:

    At the end of the loop a = 50 and b = 25

    While loop

    While loops are the simplest type of loop in PHP. The while statement will execute a block of code if and as long as a test expression is true. If the test expression is true then the code block will be executed. After the code has executed the test expression will again be evaluated and the loop will continue until the test expression is found to be false.

    In other words, PHP while loops allow you to execute the same piece of code continuously while a certain condition is true. Once the condition becomes false, the program will break out of the loop and continue processing the rest of the page.

    The flow chart shown below illustrates how the while loop works:
    while loop
    Syntax:
    while (condition) {
       //Block of code to be executed;
    }
    
    Here:
    • while () { } is the while loop block code.
    • condition is the condition to be evaluated by the while loop.
    • block of code is the code to be executed if the condition gets satisfied.
    Let’s Understand by using following Program:

    This example decrements a variable value on each iteration of the loop and the counter increments until it reaches 10 when the evaluation is false and the loop ends:

    <html>
    <body>   
      <?php
         $i = 0;
         $num = 50;      
         while ($i < 10) {
            $num--;
            $i++;
         }
         echo ("Loop stopped at i = $i and num = $num”);
      ?>  
    </body>
    </html>
    
    This will produce the following result:

    Loop stopped at i = 10 and num = 40

    The example below defines a loop that starts with $i=1. The loop will continue to run as long as $i is less than or equal to 3. The $i will increase by 1 each time the loop runs:

    <html>
    <head>
        <title>PHP while Loop</title>
    </head>
    <body>
        <?php
            $i = 1;
            while($i <= 3){
                $i++;
                echo "The number is " . $i . "<br>";
            }
        ?>
    </body>
    </html>
    
    This will produce the following result:

    The number is 2
    The number is 3
    The number is 4

    Do while Loop

    The do while loop will always execute the block of code once, it will then check the condition, and repeat the loop while the specified condition is true.

    The PHP do while loop statement allows you to execute a block of code repeatedly based on a condition. Unlike the while loop statement whose the condition is checked at the beginning of each iteration, the condition in the PHP do while statement is checked at the end of each iteration. It means the loop will execute at least once even the condition is evaluated to false.

    There is a small difference between the while and do while loops. The difference is the place where the condition is tested. As we already seen in a while loop that condition is tested at the beginning, i.e. before execution any of the statement within the while loop.

    In the case of do while loop the condition is tested after having executed the statements within the loop. This means that do while would execute its statements at least once, even if the condition fails for the first time itself.

    The following flowchart illustrates the do-while statement.
    Do While loop
    Syntax:
    do
    {
    //execute the statements;
    } 
    while (condition is true)
    
    Let’s Understand by using following Program:

    The example below sets the $x variable to 6, then it runs the loop, and then the condition is checked

    <html>
    <body>
        <?php 
            $x = 6;
            do {
                echo "The number is: $x <br>";
                $x++;
            } while ($x <= 5);
        ?>
    </body>
    </html>
    
    This will produce the following result:

    The number is: 6

    The following example will increment the value of i at least once, and it will continue incrementing the variable i as long as it has a value of less than 10

    <html>
    <body>   
      <?php
         $i = 0;
         $num = 0; 
         do {
            $i++;
         }
         
         while( $i < 10 );
         echo ("Loop stopped at i = $i" );
      ?> 
    </body>
    </html>
    
    This will produce the following result:

    Loop stopped at i = 10

    Nested Loop

    Nested loop is a loop within another loop is known as nested loop. First the inner loop is executed then outer. The depth of nested loop depends on the complexity of a problem. We can have any number of nested loops as required. Consider a nested loop where the outer loop runs n times and consists of another loop inside it. The inner loop runs m times. Then, the total number of times the inner loop runs during the program execution is n*m.

    How this works is that the first pass of the outer loop triggers the inner loop, which executes to completion. Then the second pass of the outer loop triggers the inner loop again. This repeats until the outer loop finishes. Of course, a break within either the inner or outer loop would interrupt this process.

    Types of nested loops:
    • Nested while loop
    • Nested do-while loop
    • Nested for loop
    Nested while loop

    A while loop inside another while loop is called nested while loop.

    Syntax of Nested while loop:
    while (condition1)
    {
        statement(s);
        while (condition2)
        {
            statement(s);
            ... ... ...
        }
        ... ... ...
    }
    
    Example Using nested while loop
    <?php
    int $i = 1 , $j = 1;
    while( $i < 3 )
    {
        while( $j < 3 )
        {
            echo ‘i am programmer  ‘;
            $j++;
        }
        echo ‘<br />’;
        $i++;
    }
    ?>
    
    Output:

    i am programmer i am programmer
    i am programmer i am programmer

    Nested do-while loop

    A do-while loop inside another do-while loop is called nested do-while loop.

    Syntax of Nested do-while loop:
    do
    {
        statement(s);
        do
        {
            statement(s);
            ... ... ...
        }while (condition2);
        ... ... ...
    }while (condition1);
    
    Example Using nested while loop
    <?php
    int $i=1 , $j=2;
    do
    {
       do
       {
          echo ‘i am programmer  ‘;
          $j++;
       }while( $j < 3 )
       echo ‘<br />’;
       $i++;
    }while( $i < 3 )
    ?>
    
    Output:

    i am programmer i am programmer.
    i am programmer i am programmer.

    Nested for loop:

    A for loop inside another for loop is called nested for loop.

    Syntax of Nested for loop
    for (initialization; condition; increment/decrement)
    {
        statement(s);
        for (initialization; condition; increment/decrement)
        {
            statement(s);
            ... ... ...
        }
        ... ... ...
    }
    
    Let’s Understand by using following Program:
    <?php
        $n=5;
        for($i=1; $i<=$n; $i++)
        {
        for($j=1; $j<=$i; $j++)
        {
        echo ' * ';
        }
        echo '\n';
        }
        for($i=$n; $i>=1; $i--)
        {
        for($j=1; $j<=$i; $j++)
        {
        echo ' * ';
        }
        echo '\n ';
        }
    ?>
    
    This will produce the following result:
    *                                                          
    *  *                                                       
    *  *  *                                                    
    *  *  *  *                                                 
    *  *  *  *  *                                              
    *  *  *  *  *                                              
    *  *  *  *                                                 
    *  *  *                                                    
    *  *                                                       
    *
    

    Normally nested for loop is used. while and do while not used. Another Example of nested for loop.

    <?php
    for ($i = 1; $i < 5; $i++) {
        for ($j = 1; $j <= $i; $j++) {
            echo " * ";
        }
        echo '<br />';
    }
    ?>
    
    This will produce the following result:
    *
    * *
    * * *
    * * * *
    
    Another Example of nested for loop.
    ';
    }
    ?>
    
    This will produce the following result:
          * 
         * * 
        * * * 
       * * * *
    
    There are several statements in PHP that you can use to make decisions:
    • The if statements
    • The if…else statement
    • The if…elseif…. else statement
    • The switch…case statement

    We will explore each of these statements in the coming sections.

    If else

    The if statement is used to execute a block of code only if the specified condition evaluates to true. This is the simplest PHP’s conditional statements and can be written like:

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

    The if, else statement executes some code if a condition is true and another code if that condition is false. Two conditions can be implemented on if else statement.

    You can enhance the decision-making process by providing an alternative choice through adding an else statement to the if statement. The if…else statement allows you to execute one block of code if the specified condition is evaluates to true and another block of code if it is evaluates to false.

    It can be written, like this:
    if(condition) {
        // Code to be executed if condition is true
    } else {
        // Code to be executed if condition is false
    }
    
    Flow diagram of if else statement
    If Else
    Let’s Understand by using following Program

    The following example will output “$num is even number” if the Condition is true, Otherwise, it will output ” $num is odd number.

    <html>
    <body>
        <?php  
            $num=12;  
            if($num%2==0){  
            echo "$num is even number";  
            }else{  
            echo "$num is odd number";  
            } 
        ?>  
    </body>
    </html>
    
    Result is:

    12 is even number

    The following example will output “Have a nice weekend!” if the current day is Friday, otherwise it will output “Have a nice day!”

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <title>PHP if-else Statement</title>
    </head>
    <body>
        <?php
            $d = date("D");
            if($d == "Fri"){
                echo "Have a nice weekend!";
            } else{
                echo "Have a nice day!";
            }
        ?>
    </body>
    </html>  
    
    If else if else

    The if, elseif, else a special statement that is used to combine multiple if, else statements. elseif is a combination of if and else. It extends an if statement to execute a single statement or a group of statements if a certain condition is met. It cannot do anything if the condition is false.

    If you want to execute some code if one of the several conditions are true use the elseif statement.

    It can be written, like this:
    if (condition)
       code to be executed if condition is true;
    elseif (condition)
       code to be executed if condition is true;
    else
       code to be executed if condition is false;
    
    Flow diagram of if else statement
    flow-diagram-of-if-else-statement
    Let’s Understand by using following Program’

    The following example will output “Have a nice weekend!” if the current day is Friday, and “Have a nice Sunday!” if the current day is Sunday. Otherwise, it will output “Have a nice day!” :

    <html>
    <body>
    
      <?php
         $d = date("D");
         
         if ($d == "Fri")
            echo "Have a nice weekend!";
         
         elseif ($d == "Sun")
            echo "Have a nice Sunday!"; 
         
         else
            echo "Have a nice day!"; 
      ?>
    </body>
    </html>
    
    It will produce the following result

    Have a nice Weekend!

    Nested if

    Nested if statements mean an if block inside another if block. Shortly a control structure inside another control structure.

    It structure will look like:
    if (expression 1 )
    {
    if (expression 2 )
    {
    // statements 1
    }
    else
    {
    // Statements 2
    }
    }
    else
    {
    if ( expression 2)
    {
    // Statements 3
    }
    else
    {
    // Statements 4
    }
    }
    

    Here we can see another if ,else structure inside the if block and else block. Like this we can add any number of nested if else statements.

    Switch Case

    The switch statement is used to perform different actions based on different conditions. In addition to the if statement, PHP provides switch statement that allows you to execute a code block conditionally. PHP switch statement compares a variable or an expression against many different values and execute a code block based on the value it equals to.

    The switch statement is used to avoid long blocks of if..elseif..else code.

    It structure will look like:
    <?php
    switch(variable){
     case value1: 
     // code block 1
     break;
     case value2: 
     // code block 2
     break;
     default:     
     // default code block
     break;
    }
    ?>
    
    Let’s examine the switch statement syntax in more detail:
    • First, you put a variable or expression that you want to test within parentheses after the switch keyword.
    • Second, inside the curly braces are multiple case constructs where you put the values you want to compare with the variable or expression. In case the value of the variable or expression matches the value in a case construct, the code block in the corresponding case construct will execute. If the value of the variable or expression does not match any value, the code block in the default construct will execute.
    • Third, the break statement is used in each case or default construct to exit the entire switch statement.

    It is very important to understand that the switch statement is executed statement by statement therefore the order of case constructs is very important. If the value of the variable match a value in a case construct, PHP will execute code block in that case construct and ends the switch statement because of the break statement.

    Flow diagram of switch statement
    flow-diagram-of-switch-statement
    Let’s Understand by using following Program

    The switch statement works in an unusual way. First it evaluates given expression then seeks a lable to match the resulting value. If a matching value is found then the code associated with the matching label will be executed or if none of the lable matches then statement will execute any specified default code.

    <html>
    <body>
      <?php
         $d = date("D");
         
         switch ($d){
            case "Mon":
               echo "Today is Monday";
               break;
            
            case "Tue":
               echo "Today is Tuesday";
               break;
            
            case "Wed":
               echo "Today is Wednesday";
               break;
            
            case "Thu":
               echo "Today is Thursday";
               break;
            
            case "Fri":
               echo "Today is Friday";
               break;
            
            case "Sat":
               echo "Today is Saturday";
               break;
            
            case "Sun":
               echo "Today is Sunday";
               break;
            
            default:
               echo "Wonder which day is this ?";
         }
      ?>
    </body>
    </html>
    
    It will produce the following result:

    Today is Monday

    Jump Statements (Break, Continue, Exit)

    In PHP jump statements are mainly used to transfer control to another part of our program depending on the conditions. These statements can be used to jump directly to other statements, skip a specific statement and so on. Jump statements allow you to exit a loop, start the next iteration of a loop, or explicitly transfer program control to a specified location in your program

    Sometimes you may want to let the loops start without any condition and allow the statements inside the brackets to decide when to exit the loop. There are three special statements that can be used inside loops: Break, Continue and Exit which are discussed in the following sections.

    Break Statement:

    Break ends execution of the current structure. Break accepts an optional numeric argument which tells it how many executions of nested structures to be interrupted.

    Uses of Break:
    • A break statement can be used to terminate or to come out from the loop or conditional statement unconditionally.
    • It can be used in switch statement to break and come out from the switch statement after each case expression.
    • Whenever, break statement is encounter within the program then it will break the current loop or block.
    • A break statement is normally used with if statement.
    Let’s Understand by using following Program

    The following program demonstrates the use of break statement. Loop will be terminated as soon as the counter value becomes greater than 5.

    <?php
       for( $i = 1; $i <= 10 ; $i++ )
       {
            if ($i > 5)
                break;    // terminate loop 
            echo "$i"."</br>" ;
       }
    ?>
    
    Example with argument:
    <?php
       $x = 2 ;
       while($x)
       {
            for($j =0 ; $j ++)
            {
                echo $j * $x ;
              
                if($j * $x >= 10)
                {
                    break 2;
                }
                
            }
          $x ++ ;
       }
    ?>
    
    Output of code:

    0 2 4 6 8 10

    Continue Statements:

    A continue statement can be used into the loop when we want to skip some statement to be executed and continue the execution of above statement based on some specific condition. Similar to break statement, continue is also used with if statement. When compiler encounters continue, statements after continue are skipped and control transfers to the statement above continue.

    continue-statements
    Let’s Understand by using following Program

    The following example uses the continue statement to print upper and lower a to z alphabets:

    <?php
       for ( $i = 65 ; $i <= 122 ; $i++ )   // loop through ASCII value for a to z
       {
           if($i >= 91 && $i <= 96)
                  continue ;       // skip unnecessary special characters.
           
              echo "| $i "."</br>" ;   // print character equivalent for ASCII value. 
       }
    ?>
    

    In the following example, the list of odd numbers between 1 to 10 have printed. In the while loop we test the remainder (here $x%2) of every number, if the remainder is 0 then it becomes an even number and to avoid printing of even numbers continue statement is immediately used and the control passes to the beginning of the loop.

    <?php
        $x=1;
        echo 'List of odd numbers between 1 to 10 <br />';
        while ($x<=10)
        {
        if (($x % 2)==0)
        {
        $x++;
        continue;
        }
        else
        {
        echo $x.'<br />';
        $x++;
        }
        }
    ?>
    
    Output

    List of odd numbers between 1 to 10
    1
    3
    5
    7
    9

    Exit Statement:

    The exit () function terminates execution of the script. It prints status just before exiting. Exit Output a message and terminate the current script.

    The exit () function prints a message and exits the current script.

    This function is an alias of the die() function.

    Syntax:

    xexit(message)

    Message Description

    Specifies the message or status number to write before exiting the script. The status number will not be written to the output.

    Example

    Print a message and exit the current script:

    <?php
    $site = "https://www.w3schools.com/";
    fopen($site,"r")
    or exit("Unable to connect to $site");
    ?>
    
    Parameters:
    void exit ([ string $status ] )
    void exit ( int $status )
    

    status

    • If status is a string, this function prints the status just before exiting.
    • If status is an integer, that value will be used as the exit status and not printed. Exit statuses should be in the range 0 to 254, the exit status 255 is reserved by PHP and shall not be used. The status 0 is used to terminate the program successfully.
    Return Values

    No value is returned.

    exit status example
    <?php
    //exit program normally
    exit;
    exit();
    exit(0);
    //exit with an error code
    exit(1);
    exit(0376); //octal
    ?>
    
    Summary
    • The conditional statements make your computer program to respond according to their inputs
    • if statement: executes some code if one condition is true.
    • if else statement: executes some code if a condition is true and another code if that condition is false.
    • If, elseif, else statement: executes different codes for more than two conditions.
    • switch statement: selects one of many blocks of code to be executed.
    • Jump statements can be used to jump directly to other statements, skip a specific statement and so on.

    Enrolled Yourself In Live Training – PHP Training

    Copyright 1999- Ducat Creative, All rights reserved.