Php Loops

    
     This article will show you how php loops are working

  • while
  • The while loop executes a block of code while a condition is true.
    Syntax:
    while (condition)
      {   code that will be executed;   }

    Example

    This example  defines a loop that starts with i=1. The loop will continue 
    to run until i is less than, or equal to 5. i will increase by 1 in each iteration:
    
    <html>
    <body>
    <?php
    
    $k=1;
    while($k<=5)
       {
      echo "The loop number is " . $k . "<br />";
      $k++;
      }
    
    ?>
    </body>
    </html>
    
    
    Result:
    The loop number is 1
    The loop number is 2
    The loop number is 3
    The loop number is 4
    The loop number is 5

  • do...while
  • The do...while statement will always execute the block of code once, then check the condition, and repeat the loop while the condition is true.
    Syntax:
    do
    { 
      code that will be executed;
    }
    while (condition);

    Example


    The example below defines a loop that starts with i=1. It will then increment 
    i with 1, and write some result. Then condition is checked, and the loop 
    will continue to run until i is less than, or equal to 5:
    
    <html>
    <body>
    <?php
    
    $k=1;
    do
       {
      $k++;
      echo "The loop number is " . $k . "<br />";
      }
    while ($k<=5);
    
    ?>
    </body>
    </html>
    
    Result:
    The loop number is 2
    The loop number is 3
    The loop number is 4
    The loop number is 5
    The loop number is 6

  • for
  • The for loop is used when you know in advance how many times the script should run.
    Syntax:
    for (init; condition; increment)
    {
      code that will be executed;
    }

    Example

    The example below defines a loop that starts with i=1. The loop will continue 
    to run as long as the variable i is less than, or equal to 5. The 
    variable i will increase by 1 each time the loop runs:
    
    <html>
    <body>
    <?php
    
    for ($k=1; $k<=5; $k++) 
     {
      echo "The loop number is " . $k . "<br />"; 
    }
    
    ?>
    </body>
    </html>
    
    Result:
    The loop number is 1
    The loop number is 2
    The loop number is 3
    The loop number is 4
    The loop number is 5

  • foreach
  • The foreach loop is used to loop through arrays.
    Syntax:
    foreach ($array as $value)
    {
      code that will be executed;
    }
    For every iteration, the value of the current array element is assigned to $value (and the array pointer is moved by one) - so on the next iteration, you will be point to next value.

    Example


    The following example shows a loop that will print the values of  
    the array:
    
    <html>
    <body>
    <?php
    
    $x=array("First","Second","Third");
    foreach ($x as $value {
      echo $value . "<br />"; 
    }
    
    ?>
    </body>
    </html>
    
    Result:
    First
    Second
    Third

No comments: