Safcode Institute by Sir Safder





  • Loops in PHP

    Loop are used to execute the same block of code again and again,
    as long as the certain condition is true. 
    In PHP we have following type of loops are as given:
    1. While
    2. Do while
    3. For
    4. Foreach
     
    1) While
    While loop is the simplest and easy type of loop in php.
    Its only works when the condition is true.
    
    Example:
    <?php
    $abc = 1;
    while($abc <= 5) 
    {
      echo "The Value of ABC is: $abc <br>";
      $abc++;
    }
    ?>
    
    Output:
    The Value of ABC is: 1
    The Value of ABC is: 2
    The Value of ABC is: 3
    The Value of ABC is: 4
    The Value of ABC is: 5
    
    
    2) Do-while
    Do-while loop is similar to while loop.
    while loop never execute if the condition is false.
    But do-while loop execute atleast one time if the 
    condition is false, otherwise its works like while loops
    
    Example: Same as while loop.
    <?php
    $x = 1;
    
    do {
      echo "The Value of ABC is: $x <br>";
      $x++;
    } while ($x <= 5);
    ?>
    
    Output:
    The Value of ABC is: 1
    The Value of ABC is: 2
    The Value of ABC is: 3
    The Value of ABC is: 4
    The Value of ABC is: 5
    
    3) For
    For loop is the most common loop in PHP. 
    For loop is used when we know how many times of code 
    are execute, otherwise we use while loop.
    In for loop we put all the statement in single line.
    Uou can see the example.
    
    Example:
    <?php  
    for ($x = 0; $x <= 10; $x++) 
    {
      echo "The Value of ABC is: $x <br>";
    }
    ?>  
    
    Output: 
    The Value of ABC is: 0
    The Value of ABC is: 1
    The Value of ABC is: 2
    The Value of ABC is: 3
    The Value of ABC is: 4
    
    4) For-each
    foreach loop works only on arrays and objects.
    foreach loop works until it reaches the last element of array.
    
    Example:
     
    <?php  
    $colors = array("HTML", "CSS", "PHP", "MYSQL");
    
    foreach ($colors as $value) 
    {
      echo "$value <br>";
    }
    ?>
    
    Output: 
    HTML
    CSS
    PHP
    MYSQL
    



  • You Can Also Watch Our Tutorial