Loops In PHP

Similar to other programming languages, PHP uses loops to repeatedly execute a statement or a group of statements up until and unless a certain condition is fulfilled. By doing this, the user may avoid wasting time and energy on repetitive coding.

Types of Loop in PHP
  1. for loop
  2. while loop
  3. do-while loop
  4. foreach loop

1. for loop

For loop is a type of control structure that iterates over a block of code until a certain condition is met. For loops are commonly used to repeat a certain block of code for a certain number of iterations.

In PHP, the for loop function is used to iterate a set of code over a specified number of times. If you specify the number of iterations, you should use the for loop; otherwise, you should use a while loop.

Initialization Expression: We must set the loop counter’s initial value using this expression. such as: $num = 1;
Test Expression: The condition in this expression needs to be tested. We will run the body of the loop and go on to updating the expression if the condition evaluates to true; otherwise, we will end the for loop. For example: $num <= 10;
Update Expression: This expression increases or decreases the loop variable by a certain amount following the execution of the loop body. as in the case of $num += 2;

Syntax:

for ( initializing value; condition checking; increment)

{

Code to be executed

}

Example:

for ($num = 2; $num <= 8; $num += 2) { echo $num ; } ?>

Output: 2, 4, 6, 8

2. while loop

While loop: The while loop functions similarly to a for loop in that it analyzes the condition at the beginning of the loop to see if it is true, at which point it enters the loop and begins executing the block of statements, and goes on executing it as long as the condition holds true.

Syntax:

while(condition){

// Statements to be executed

}

Example:

$num = 4;

while ($num < 10) { $num += 2; echo $num, “n”; } ?>

Output: 6, 8, 10

3. do-while loop

The condition is checked at the conclusion of each loop iteration in the while loop, which is a variant of the do-while loop. A do-while loop repeats a statement for as long as the specified condition is true after executing a block of code once and evaluating the condition.

Syntax:

Do

{

Statements to be executed;

} while (condition is true);

Example:

Output: 6, 8, 10

4. foreach loop

An array can be iterated over using this loop. An array element is allocated to each loop counter, and the next counter is moved to the next element.

Syntax:

foreach($array as $value)

{

// Statements to be executed

}

Example:

Example: 2, 3, 4, 5, 6, Sagar, Ganesh, Manas