• Like any other language, in PHP loop is used to execute a statement or a block of statements, multiple times until and unless a specific condition is met.
  • Loops helps the user to save both effort and time of writing the same code multiple times.
  • PHP supports four types of looping techniques, they are:
    1. For loop
    2. While loop
    3. Do-while loop
    4. Foreach loop

For loop

  • For loop is used when the user knows in advance, how many times the block needs to execute.
  • The number of iterations is known beforehand and these types of loops are also known as entry-controlled loops.
  • Initialization expression, test expression, update expression are the three main parameters to the code.

Syntax

for (initialization expression; test condition; update expression) {
// code to be executed
}

While loop

  • While loop is also an entry control loop like for loop condition.
  • First it checks the condition at the start of the loop and if its true then it enters the loop and executes the block of statements, and goes on executing it as long as the condition holds true.

Syntax

             while (if the condition is true) {
// code is executed
}

Do-while loop

  • Do while loop is an exit control loop which means that it first enters the loop, executes the statements, and then checks the condition.
  • Using do-while a statement is executed at least once.
  • The program is executed as long as the condition holds true, after executing once.

Syntax

do {

//code is executed

} while (if condition is true);

Foreach loop

  • Foreach loop is used to iterate over arrays and for every counter of loop, an array element is assigned and the next counter is shifted to the next element.

Syntax

foreach (array_element as value) {
//code to be executed
}

 

Categorized in: