Lesson 9 – PHP Loops

Sometimes, you have to execute the same piece of code again and again or for a specific number of times. We use loops to accomplish this very task. There are actually three types of loops in PHP. We will study them one by one in the following lines.

The While Loop

The While is the simplest of all the loops in PHP. It only loops through a piece of code if it fulfills a certain condition. The process keeps on repeating as long as you want it to repeat. Here is the syntax of While Loop.

<?php 

while (condition) {
    Execute the code if condition is true; 
 }
 ?>

The following is an example of while loop.

<?php 
  $counter = 0;
  
  while ($counter < 5) {
      echo "Hello my dear friends!"; 

      $counter = $counter + 1; 
  }
 
 ?>

In the above example, we have created an initializer or counter that is $counter which starts at 0. Apache will keep executing the code unless the counter reaches 5. This is because it also increments the counter by 1 after every iteration of the loop. As soon as the counter reaches 5, the statement becomes false and the loop stops.

Here is the output of the above code.

The For Loop

If you already know how many times you will execute code, you will use the For Loop. Here is its syntax.

<?php 
   for (initialization; condition; increment){
    Execute the code;
 }
 ?>

In for loop, you create the initializer inside the loop as compared to while loop where initializer is created outside of the loop. The remaining syntax is almost the same. The following is an example of a For Loop.

<?php 
  for ($counter = 0; $counter < 5; $counter++) {
      echo $counter;
  }
 
 ?>

In the above example, we have created an initializer, $ counter, which starts at 0. The Apache tests the condition that is whether or not the counter is less than 5. Finally, Apache increments the counter by 1. The output of the above code will be 01234 because the loop starts at zero and terminates at 4 as the initializer is smaller than 5.

The Foreach Loop

The Foreach loop is the most powerful loop in PHP. Its basic purpose is to go through an array and process all of its values. Unlike While and For loops, you don’t need to tell Foreach loop when to stop because it already knows that. Have a look at the following example.

<?php 
  $numbers = array(23, 45, 66, 88, 99);

  foreach ($numbers as $number) {
      echo $number . "<br>"; 
  }
 ?>

In the above example, we create an array called $numbers. Then we place the array inside the For Loop. The key “as” assigns the $number variable to each of the array’s values. Therefore, the $number will be assigned to the first value that is 23 when the loop iterates for the first time. It will be assigned to the second value when loop iterates for the second time. The process will continue until the loop gets to the end.

The outcome of the above code is as under.

In the next lecture, we will talk about functions in PHP.