PHP Loops

PHP Loops

PHP Loops are used to repeat a sequence of statements until the condition is true. Or in simple words, we can say that Loops are used to run the block of code again and again until the condition is true.
PHP supports following different types of loops:

  • while – loops through a block of code as long as the given condition is true
  • do…while – loops through a block of code once, and then repeats the loop as long as the given condition is true
  • for – loops through a block of code a given number of times
  • foreach – loops through a block of code for each element in an array

PHP while Loop

loops through a block of code as long as the given condition is true.

while(condition){
    // Code to be executed
}

PHP do while Loop

loops through a block of code once, and then repeats the loop as long as the given condition is true.

do{
    // Code to be executed
}
while(condition);

PHP for Loop

loops through a block of code a given number of times.

for(initial value; condition; increment coutner){
    // Code to be executed
}

PHP foreach Loop

loops through a block of code a given number of times.

foreach($array as $value){
    // Code to be executed
}