Codingtree

Often an application needs to run in a loop to execute a task repetitively. For example, if we have an array of user names and if we are looking for a specific user, then we need to run in a loop and keep iterating until we find the name that matches the user.

For such looping-based tasks, PHP provides four constructs: (1) while loop (2) do-while loop, (3) for loop, (4) foreach loop.

A loop depends upon a specified condition to determine whether to continue further or to terminate/stop. The loop would periodically check if the condition (based on a variable or an expression) is true -- it will typically run as long as the condition is true.

Clearly, for the above scheme to work, the loop variable or the loop expression must also change as the loop progresses; if it does not, then the loop would simply run forever! Though, there are valid programs that require a loop to run forever, a vast majority of programs would in fact require the loop to stop at some point.

Sometimes, we articulate the scheme of condition check into three stages: initialization (where the loop variable or the expression is initialized), loop-increment (where the loop variable or the expression is changed), and loop-condition (where we check if the condition is still true).

We use a simple program (provided below) to demonstrate the above looping variants of while, do-while, for, and foreach. For a while loop, the looping happens as long as the specified condition is true ("$counter < 3"). After every round, we increase the value of $counter inside the loop so that the loop can terminate after some time. The do-while variant also has a similar format, except that the while sits at the end of the loop block (don't forget the semicolon at the end of the while!). The third variant is the "for" loop. This method cleanly integrates all the three tasks of looping in the beginning expression itself: loop-initialization ("$counter=0"), loop-increment ("$counter++"), and loop-condition ("$counter < 3"). The "foreach" method is the fourth variant and is used to traverse elements of an array and can be used only with arrays. At each pass, we assign the value of the current element of the array to the variable $element.

 <?php
 $username_array[3];

 /* Names of users who have signed up for the application */
 $username_array[0] = "James Fulton";
 $username_array[1] = "Thomas Kipling";
 $username_array[2] = "Karuna Simon";

 echo "Let us print using a while loop <br>";
 $counter = 0;  
 while ($counter < 3) { 
     echo "[i: $counter] user name: $username_array[$counter] <br>";
     $counter++;
 }        

 echo "<br>Let us print using a do-while loop <br>"; 
 $counter = 0;  
 do {
     echo "[i: $counter] user name: $username_array[$counter] <br>";
     $counter++;
 } while ($counter < 3); 

 echo "<br>Let us print using a for loop <br>";
 for ($counter=0; $counter < 3; $counter++) {
     echo "[i: $counter] user name: $username_array[$counter] <br>";
 }

 echo "<br>Let us print using a foreach loop <br>";
 foreach ($username_array as $element) {
     echo "user name: $element <br>";
 }
 ?>

The difference between while and do-while methods is worth noting. With the do-while method, the loop block is executed at least once. This happens because even if the while condition is false, the program must run starting from "do" till the point where it reaches the "while" condition. Thus, for cases, where we need to run the loop for the first round, irrespective of the condition, we should consider the do-while method.

Now, let us run the above program by loading this page on a browser. The browser shows the following:

 Let us print using a while loop
 [i: 0] user name: James Fulton
 [i: 1] user name: Thomas Kipling
 [i: 2] user name: Karuna Simon

 Let us print using a do-while loop
 [i: 0] user name: James Fulton
 [i: 1] user name: Thomas Kipling
 [i: 2] user name: Karuna Simon

 Let us print using a for loop
 [i: 0] user name: James Fulton
 [i: 1] user name: Thomas Kipling
 [i: 2] user name: Karuna Simon

 Let us print using a foreach loop
 user name: James Fulton
 user name: Thomas Kipling
 user name: Karuna Simon

Continue and Break

Running in a loop and terminating when the specified condition becomes false is not always enough. Sometimes, an application may wish to be more selective! A program might wish to either skip some of the records or to break out of the loop once a certain task is complete.

PHP (like C) provides these two options via two loop-based keywords: continue and break. The keyword "continue" allows a program to skip the current record and continue with the next one. The keyword "break" allows a program to break out of the loop even though the specified loop condition might still be true.

Let us suppose that we need to print the list of users and would like to skip some of the records based on a specific criteria (for simplicity sake, we print elements with even array index). To do so, we can modify the above program to use "continue" keyword and for elements that have odd array index, we simply let "continue" skip those records.

Next, for the usage of the break keyword, let us say that we need to look for a specific username (say "Homer Simpson") and we want to print user's information. We can go in a loop and when we find "Homer Simpson", we can the "break" keyword to come out of the loop.

We modify the previous program to use these two keywords. For the sake of simplicity, we use only a "for" loop. However, these keywords would apply equally well for the remaining three loop variants as well, including the "foreach" variant. Also, we use an "if" clause to check if a given condition is true -- more on the "if" clause in the next section!

 <?php
 /* Names of users who have signed up for the application */
 $username_array[0] = "James Fulton";
 $username_array[1] = "Thomas Kipling";
 $username_array[2] = "Karuna Simon";
 $username_array[3] = "Lilly Sellers";
 $username_array[4] = "Homer Simpson";

 echo "<br>Let us skip certain records while printing <br>";
 for ($counter=0; $counter < 5; $counter++) {
     /* Skip elements with odd array index */
     if ($counter % 2 != 0) {
         continue;
     }
     echo "[i: $counter] user name: $username_array[$counter] <br>";
 }

 echo "<br>Let us find a specific record <br>";
 for ($counter=0; $counter < 5; $counter++) {
     /* Let us look for one specific record */
     if ($username_array[$counter] == "Homer Simpson") {
         echo "[i: $counter] user name: $username_array[$counter] <br>";
         break;
     }
 }
 ?>

Here is the output of the above program:

 Let us skip certain records while printing 
 [i: 0] user name: James Fulton 
 [i: 2] user name: Karuna Simon 
 [i: 4] user name: Homer Simpson 

 Let us find a specific record 
 [i: 4] user name: Homer Simpson 




comments powered by Disqus