PHP Loop – All About You Need To Know

PHP Loop Like any other language, a loop in PHP is used to execute a statement or a block of statements, multiple times until and unless a specific condition is met. This helps the user to save both time and effort of writing the same code multiple times.

PHP supports four types of looping techniques;

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

Let us now learn about each of the above-mentioned loops in detail

  1. for loop: This type of loop is used when the user knows in advance, how many times the block needs to execute. That is, the number of iterations is known beforehand. These types of loops are also known as entry-controlled loops. There are three main parameters to the code, namely the initialization, the test condition, and the counter.In for loop, a loop variable is used to control the loop. First, initialize this loop variable to some value, then check whether this variable is less than or greater than the counter value. If the statement is true, then the loop body is executed and the loop variable gets updated. Steps are repeated till the exit condition comes.
    • Initialization Expression: In this expression, we have to initialize the loop counter to some value. for example: $num = 1;
    • Test Expression: In this expression, we have to test the condition. If the condition evaluates to true then we will execute the body of the loop and go to update expression otherwise we will exit from the for a loop. For example: $num <= 10;
    • Update Expression: After executing the loop body this expression increments decrements the loop variable by some value. for example: $num += 2;
  2. while loop: The while loop is also an entry control loop like for loops i.e., it first checks the condition at the start of the loop, and if it’s true then it enters the loop and executes the block of statements, and goes on executing it as long as the condition holds true.
  3. do-while loop: This is an exit control loop which means that it first enters the loop, executes the statements, and then checks the condition. Therefore, a statement is executed at least once using the do…while loop. After executing once, the program is executed as long as the condition holds true.
  4. for each loop: This loop is used to iterate over arrays. For every counter of the loop, an array element is assigned and the next counter is shifted to the next element.
You Might Also Read  How Do I Get Rid of Hay Fever Naturally

Let’s now look at them separately. For loop, It has the following basic syntax

<?php
for (initialize; condition; increment){

//code to be executed

}
?>

HERE,

  • “for…{…}” is the loop block
  • initialize” is usually an integer; it is used to set the counter’s initial value.
  • “condition” is the condition that is evaluated for each PHP execution. If it evaluates to true, then execution of the for… loop continues. If it evaluates to false, the execution of the for… loop is terminated.
  • “increment” is used to increment the initial value of a counter integer.

How it works

The flowchart shown below illustrates how for loop in PHP works

PHP Loop and  Control Structures

How to code

The code below uses the “for… loop” to print values of multiplying 10 by 0 through to 10

<?php

for ($i = 0; $i < 10; $i++){

$product = 10 * $i;

echo "The product of 10 * $i is $product <br/>";
}

?>

Output:

The product of 10 x 0 is 0 
The product of 10 x 1 is 10 
The product of 10 x 2 is 20 
The product of 10 x 3 is 30 
The product of 10 x 4 is 40 
The product of 10 x 5 is 50 
The product of 10 x 6 is 60 
The product of 10 x 7 is 70 
The product of 10 x 8 is 80 
The product of 10 x 9 is 90 

PHP For Each loop

The PHP for each loop is used to iterate through array values. It has the following basic syntax

<?php
foreach($array_variable  as $array_values){

block of code to be executed

}
?>

HERE,

  • “for each(…){…}” is the foreach PHP loop block code
  • “$array_data” is the array variable to be looped through
  • “$array_value “ is the temporary variable that holds the current array item values.
  • “block of code…” is the piece of code that operates on the array values
You Might Also Read  PHP (Hypertext Preprocessor) - All About You Need To Know

How it works The flowchart shown below illustrates how the for… each… loop works

PHP Loop and  Control Structures

Practical examples

The code below used for each loop to read and print the elements of an array.

<?php

$animals_list = array("Lion","Wolf","Dog","Leopard","Tiger");

foreach($animals_list as $array_values){

echo $array_values . "<br>";

}

?>

Output:

Lion
Wolf
Dog
Leopard
Tiger

Let’s look at another example that loops through an associative array.

An associative array uses alphanumeric words for access keys.

<?php

$persons = array("Mary" => "Female", "John" => "Male", "Mirriam" => "Female");

foreach($persons as $key => $value){

echo "$key is $value"."<br>";

}

?>

The names have been used as array keys and gender as the values.

Output:

Mary is Female
John is Male
Mirriam is Female

While Loop

PHP While loop

They are used to execute a block of code repeatedly until the set condition gets satisfied

When to use while loops

  • While loops are used to execute a block of code until a certain condition becomes true.
  • You can use a while loop to read records returned from a database query.

Types of while loops

  • Do… while – executes the block of code at least once before evaluating the condition
  • While… – checks the condition first. If it evaluates to true, the block of code is executed as long as the condition is true. If it evaluates to false, the execution of the while loop is terminated.

While loop

It has the following syntax

<?php
while (condition){

block of code to be executed;

}
?>

HERE,

  • “while(…){…}” is the while loop block code
  • “condition” is the condition to be evaluated by the while loop
  • “block of code…” is the code to be executed if the condition gets satisfied
You Might Also Read  PHP Array - Associative, Multidimensional

How it works

The flow chart shown below illustrates how the while… loop works

PHP Loop and  Control Structures

Practical example

The code below uses the while… loop to print numbers 1 to 5.

<?php

$i = 0;

while ($i < 5){

echo $i + 1 . "<br>";

$i++;

}

?>

Output:

1
2
3
4
5

PHP Do While

The difference between While… loop and Do… while loop is done while is executed at least once before the condition is evaluated.

Let’s now look at the basic syntax of a do… while loop

<?php
do{

block of code to be executed

}
?>

while(condition);

HERE,

  • “do{…} while(…)” is the do… while loop block code
  • “condition” is the condition to be evaluated by the while loop
  • “block of code…” is the code that is executed at least once by the do… while loop

How it works

The flow chart shown below illustrates how the while… loop works

PHP Loop and  Control Structures

Practical example

We are now going to modify the while… loop example and implement it using the do… while loop and set the counter initial value to 9.

The code below implements the above-modified example

<?php

$i = 9;

do{

    echo "$i is"." <br>";

}

while($i < 9);

?>

The above code outputs:

Note the above example outputs 9 only.

This is because the do… while loop is executed at least once even if the set condition evaluates to false.

Summary

  • The for loop is used to execute a block of a specified number of times
  • The for each loop is used to loop through arrays
  • While loop is used to execute a block of code as long as the set condition is made to be false
  • The do-while loop is used to execute the block of code at least once then the rest of the execution is dependent on the evaluation of the set condition