PHP Loops

php loops

Suppose you need to print the sentence – “I’m learning php” three times. What will you do? In light of the knowledge of the previous lessons, you may print the sentence three times like the following-

<?php
     echo “I’m learning php”;
     echo “I’m learning php”;
     echo “I’m learning php”;
 ?>


If you need to print the above sentence 100 times will you write the same sentence 100 times? Well, you shouldn’t  That wouldn’t be a smart way. There is a feature in programming called looping that allows performing the same task again and again. In this lesson you’ll learn all about php loops.

PHP allows the following types of loop-

  1. while loop
  2. do-while loop
  3. for loop
  4. foreach loop

while loop

while loop is the simplest type of loops in php.

Syntax

while (expression)
  statement;

How it works

  1. When php interpreter reaches to the while keyword, it checks the value of the expression inside the parentheses.
  2. If the expression returns true, the interpreter executes the next statement.
  3. Then the interpreter returns to the while keyword again to check the expression.
  4. This loop continues until the expression after the while keyword returns false.

If there is more than one statement to be executed in the loop, then the statements can be enclosed by brackets in the following way-

while (expression){
  statement1;
  statement2;
  ....
}

Example

<?php
   $i =1;
   while($i<3){
     echo “I’m learning php.”;
     echo “<br />”;
     ++$i;
   }
?>

Output

I’m learning php.
I’m learning php.

Explanation

  1. At first, the value of the variable $i is set to 1 in line 1.
  2. In line 2, as $i (which value is 1) is less than 3, the expression returns true and the interpreter enters into the statements inside the brackets.
  3. In line 3, it prints “I’m learning php.”.
  4. Line 4 takes the cursor to the new line.
  5. In line 5, the incrementing operator increases the value of $i by 1 and makes its value 2.
  6. Then the interpreter goes back to check the expression in while again in line 2. Now, the value of $i is 2, so the expression $i<3 returns true again and the interpreter executes those lines from 3 to 5.
  7. In line 3, it prints “I’m learning php.”.
  8. Again, line 4 takes the cursor to the new line.
  9. In line 5, the incrementing operator increases the value of the $i by 1 and makes its value 3.
  10. Then the interpreter goes to check the expression in while again. Now, the value of $i is 3, so the expression $i<3 returns false as 3 is not less than 3.

The interpreter can’t enter into the brackets and exits it.

do-while loop

  1. do…while loop is a variant of while loop with a slight difference.
  2. In while loop, for the first time checking, the loop will not run if the expression returns false. On the other hand, do…while loop will run the loop at least once no matter whether the expression returns true or false for the first time checking.
  3. In short, while loop checks the expression (condition) at first; and the do…while loop checks the expression (condition) at last. That’s why, the loop always runs at least once in do…while loop.

Syntax

do
  statement
while(expression);

How it works

  1. When php interpreter reaches to the do keyword, it enters into the next parts of the loop.
  2. The interpreter executes the following statement after the do keyword.
  3. Then, it checks the expression in the parenthesis after the while keyword.
  4. If the expression returns true, the loop starts again from the step 1.
  5. If the expression returns false, php interpreter exists the loop.

If there is more than one statement to be executed in the loop, then the statements can be enclosed by brackets like the following way-

do{
  statement1;
  statement2
  ...
}while(expression);

Example

<?php
     $i =1;
     do{
         echo “I’m learning php.”;
         echo “<br />”;
         ++$i;
     }while($i<3)
?>

Output

I’m learning php.

Explanation

  1. At first, the value of the variable $i is set to 1 in line 1.
  2. In line 2, php interpreter enters into the brackets to executes the statements.
  3. In line no 3, it prints “I’m learning php.”.
  4. Line 4 takes the cursor to the new line.
  5. In line 4, the incrementing operator increases the value of the $i by 1 and makes its value 2.
  6. The expression in the parentheses after the while returns true (as 2 is less than 3), so the loop starts again.
  7. In line no 3, it again prints “I’m learning php.”.
  8. Line 4 takes the cursor to the new line.
  9. In line 4, the incrementing operator increases the value of the $i by 1 and makes its value 3.
  10. The expression in the parentheses after the while returns false (as 3 is not less than 3), so the loop ends.

for loop

for loop is the most complex loops in php, though it is not that much complex.

Syntax

for(expression1; expression2; expression3)
  statement;
  1. The for loop consists of the keyword for followed by three expressions separated by semicolons and enclosed within parentheses.
  2. expression1 or initialization expression: expression1 sets the value of the counter. The function of the counter is to count how many times the loop iterates. expression1 executes only once no matter how many times the loop iterates.
  3. expression2 or condition expression: Before each iteration, expression2 tests whether the loop should continue or stop.
  4. expression3 or modification expression: After each loop iteration, the expression3 determines how the loop counter should be altered. The loop counter can be incremented or decremented.

How it works

  1. When the php interpreter reaches to the for keyword, it executes expression1 and sets the value of the counter.
  2. Then, the interpreter checks expression2 to see whether the loop should continue. If expression2 returns true the loop continues otherwise, the loop stops.
  3. If expression2 returns true, the statement next to the closing parentheses is executed.
  4. Then, expression3 is executed. It may increment or decrement the counter.
  5. At this point the interpreter goes to step 2 again.

If there is more than one statement to be executed in the loop, then the statements can be enclosed by brackets like the following way-

for(expression1; expression2; expression3){
  statement1;
  statement2;
  ….
}

Example

<?php
     for($i=1; $i<3; $i++){
         echo “I’m learning php.”;
         echo “<br />”;
     }
?>

Output

I’m learning php.
I’m learning php.

Explanation

  1. The for loop starts and sets the value of the counter variable $i to 1 in the first expression in line 1.
  2. Then, it checks the condition of expression2. This returns true as the counter ($i which value is 1) is less than 3.
  3. So, the interpreter enters into the statements inside the curly brackets and, prints the line in line 3. Line 4 takes the cursor to the next line.
  4. Then the interpreter returns to the third expression in line 1 in the parentheses and increase the value of counter variable by 1 and make it 2.
  5. Then, it checks the condition in expression2. This returns true as the counter variable which value is 2 is less than 3.
  6. So, the interpreter enters into the statements inside the curly brackets and, prints the line in line no 3. Line 4 takes the cursor to the next line.
  7. Then the interpreter returns to the third expression in line 1 in the parentheses and increases the value of counter variable by 1 and make it 3.
  8. Then, it checks the condition in expression2. This time, it returns false as the counter variable which value is 3 is not less than 3.
  9. The loop exits.

foreach loop

  1. foreach loop is specially designed to access all the elements of an array in the fastest and the easiest way.
  2. foreach works only in arrays and in objects

Syntax

foreach($array as $value)
    statement;

The foreach loop consists of the keyword foreach, then a pair of parentheses that contains an array followed by the keyword as and then a variable that will hold each successive value of the each  element of the array as the loop progresses.

When the key of each array element is needed to access then the following syntax is used-

foreach($array as $key => $value)
  statement;

How it works

  1. When php interpreter reaches to the foreach loop, it takes the first element of the array $array and places it in the variable $value.
  2. Then, the interpreter executes the statement that is immediately after the foreach’s closing parentheses.
  3. Then, the interpreter goes to step 1.

This process continues as long as the last element of the array remains.

If there is more than one statement to be executed in the loop, then the statements can be enclosed by brackets like the following way-

foreach($array as $value){
  statement1;
  statement2;
  ....
}

Example

<?php
   $month=array("January", "February");
   foreach($month as $value){
     echo $value;
     echo "<br />";
   }
?>

Output
January
February.

Explanation

  1. An array named month that has two elements January and February is declared in line 1.
  2. In line 2, the loop starts. The first element (January) of the array $month is taken and place it in the variable $value.
  3. The interpreter enters into the curly brackets and prints the variable $value( that is January) in line 4
  4. Line 5 takes the cursor to the next line.
  5. Then the interpreter returns to foreach loop again in line 2.
  6. The interpreter takes the next element (In this case February) of the array $month and place it in the variable $value.
  7. The interpreter enters into the curly brackets and prints the variable $value( that is February) in line no 4
  8. Line 5 takes the cursor to the next line.
  9. Then the interpreter returns to foreach loop again in line 2.
  10. The interpreter looks for the next element of the array $month. As there is no element left, the loop ends here.

break

break statement is used to end the current execution of the following control structures-

  1. for
  2. foreach
  3. while
  4. do…while
  5. switch

Example

<?php
 $month=array("January", "February", “March”, “April”, “May”, “June”, ”July”, “August”, “September”, “October”, “November”, “December”);
 foreach($month as $value){
     echo $value;
     echo "<br />";
     if($value == “April”)
         break;
 }
?>

Output
January
February
March
April

Explanation

  1. foreach loop takes element from the array $month from the beginning one by one and place it in the variable $value and enters inside the curly brackets and prints those.
  2. The loop continues printing the names of the month until it reaches April.
  3. When the value of the variable is “April”, the condition in line 5 returns true and php interpreter executes the break statement and the break ends the foreach loop.

Variation

  1. There is a numeric optional argument that break can accept. It tells how many enclosing control structures are to be broken out of.
  2. break only accepts positive numbers.

Example 1

<?php
 $month=array("January", "February", “March”, “April”, “May”, “June”, ”July”, “August”, “September”, “October”, “November”, “December”);
 foreach($month as $value){
     echo $value;
     echo "<br />";
     if($value == “April”)
         break 1;
 }
?>

Output
January
February
March
April

Explanation

This is the same example as the last one is. Only difference is the use of argument 1 after break in line 6. It tells to break out one level of enclosing control structure that means the current foreach loop.

Example 2

<?php
 $month=array("January", "February", “March”, “April”, “May”, “June”, ”July”, “August”, “September”, “October”, “November”, “December”);
 foreach($month as $value){
     switch ($value){
         case "February":
             echo "February";
            echo "<br />";
             break 2;
         default:
             echo "January";
             echo "<br />";
             break;
     }
 }
?>

Output
January
February

Explanation

  1. The foreach loop at first takes the first element (January) of the array $month, set the value in the $value variable and enters into its curly brackets (line 2).
  2. The value of the variable $value in the parenthesis after the switch is January (line 3).
  3. As January doesn’t match with the case statement (that means case “February”); so, the default statement is executed and January is printed.
  4. Then, the interpreter goes back to the foreach loop again and take the next element (February) of the array $month, set the value in the $value variable and enters into its curly brackets.
  5. The value of the variable $value in the parenthesis after the switch is February.
  6. This time, February is matched with the case statement; so, the statements inside is executed and February is printed.
  7. Now, after printing February, when the interpreter comes to line 7 (break 2;), it tells interpreters to break out of 2 levels enclosing structures. Therefore, the two control structures switch and foreach are broken out.

continue

continue statement is used to end the current execution of the following control structures-

  1. for
  2. foreach
  3. while
  4. do…while
  5. switch

And it doesn’t execute remaining statements in the current loop; rather, it goes to check the condition of the loop to start the next iteration.

Example

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

Output
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday

Explanation

  1. foreach loop takes element from the array $day one by one and executes the statements inside its curly brackets without executing the if condition until it reaches to the element which value is January.
  2. When the loop takes the element January, it sets the value of $value as January and enters inside the curly brackets, this time, the if condition returns true and the continue statement is executed.
  3. As the continue statement is executed, the remaining statements after it are not executed and then the interpreter goes back to the foreach loop to execute the remaining elements of the array.

Variation

  1. There is a numeric optional argument that continue can accept. It tells how many enclosing loops are to be skipped.
  2. continue only accepts positive numbers.

Example 1

<?php
 $day=array("Monday", "Tuesday", "Wednesday", "Thursday", "January", "Friday", "Saturday", "Sunday");
 foreach($day as $value){
     if($value == "January")
         continue 1;
     echo $value;
     echo "<br />";
 }
?>

Output
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday

Explanation

This is the same example as the last one is. The only difference is that the argument 1 is used after continue in line 5. It tells interpreter to skip 1 level (current level) of enclosing loop.

Example 2

<?php
 $day=array("Monday", "Tuesday", "Wednesday", "Thursday", "January", "Friday", "Saturday", "Sunday");
 foreach($month as $value){
     switch ($value){
         case "January":
             continue 2;
             break;
         default:
             echo $value;
             echo "<br />";
             break;
     }
 }
?>

Output
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday

Explanation

  1. The foreach loop takes elements from the array $day one by one and sets the value in the $value variable and enters into its curly brackets.
  2. Up to January, the value of $value doesn’t match with the case statement, so the default statement executes and prints the name of the days

When the value of the $value is January, it matches with the case statement and continue 2 is executed. It tells interpreter to skip 2 levels of enclosing loop. So, it skips current switch and the current foreach loop and goes to the next element of the foreach loop.

‹‹ PHP Conditional Statements : Previous Lesson Next Lesson: PHP File-Inclusion ››