1. Loops

    Sometimes we need execute some code repetitively based on a condition. In this situation we can use loops to perform that task.

    In PHP, we have the following looping statements:

    • while - loops through a block of code until specified condition is true

    • do...while - loops through a block of code once, and then repeats the loop until the specified condition is true

    • for - loops through a block of code a specified number of times

    • foreach - loops through a block of code for each element in an array

    while loop

    The while loop is used to execute a block of statements for a definite number of times, depending on a condition. The while loop statement always checks the condition before executing the statement with in the loop.The loop will continues its the execution until the condition evaluates to false.

    Example

    <?php

    $a=1;

    while($a<=10)

     {

     echo "The number is:     $a<br>";

     $a++;

     }

    ?>

    do ... while Loop

    This loop is a same as the while loop, The do  block will executes at least once in the begining of the loop.

    do

     {

     code to be executed;

     }

    while (condition is true);

     

    For loop

    The for loop is used to execute the code for a specific number of times.The same procedure as for loop.

    for (init counter; test counter; increment counter)

     {

     code to be executed;

     }

    The initialization expression initialize the expression for the for loop statement.It executes once at the begining of the loop. The termination expression determines when to terminate the while loop. At the beginning of the loop, this expression evaluated for each iteration. if the expression evaluates to false, the loop terminates. Then, the decrement/increment expression gets invoked after each iteration.

    foreach Loop

    The foreach loop only used to loop through array, It iterate for each key/value pair in an array.

    foreach ($array as $value)

     {

     code to be executed;

     }