PHP for loop

      No Comments on PHP for loop

PHP for loop is used when you know how many times you want statement or a block of statements to be executed.

PHP for loop

Syntax:

for (initialization; condition; increment)
{
    code to be executed;
}
  • Initialization: Initialize the loop counter value. For example: $x=1; .
  • Condition: Condition is evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it evaluates to FALSE, the loop ends. For example: $x<=10; .
  • Increment:Increase the loop counter values. For example: $x++ ;.

PHP for loop

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

    Result:
    0
    1
    2
    3
    4
    5
    This program is basic for loop program to print numbers. The loop will execute till $x<=5;. After every iteration $x is incremented by 1.

  2. Looping through letters is possible.
    for($col = 'R'; $col != 'AD'; $col++)
    {
        echo $col.' ';
    }
    

    Result: R S T U V W X Y Z AA AB AC.
    Take note that you can't use $col < 'AD'. It only works with !=

  3. PHP foreach loop

    The foreach loop works only on arrays, and is used to loop through each key/value pair in an array.
    Syntax

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

    Example:

     <?php
    $days = array("Monday", "Tuesday", "Wednesday" , "Thursday" , "Friday" ,"Saturday" ,"Sunday");
    
    foreach ($days as $value) {
        echo "$value <br>";
    }
    ?> 
    

    Result:
    Monday
    Tuesday
    Wednesday
    Thursday
    Friday
    Saturday
    Sunday

    Difference between for and for each loops

    For can be used to run statements for a fixed number of times, foreach can be used to run statements for dynamically generated arrays(may be result of database query).We can also used for loop for dynamically generated array(may be result of database query) but foreach is the ideal way to iterate dynamic array. The reason behind this, we don't know the index of array as it may be associate result from database query. So if we use foreach than it will iterate the result one by one.

    For loop can be more optimized if we know the count of array and index of array while foreach is better when we have dynamic array without knowing index of array and size of an array.

Leave a Reply

Your email address will not be published. Required fields are marked *