Types of Loops in PHP || Server Side Scripting || BCIS Notes

Types of Loops in PHP || Server Side Scripting || BCIS Notes

Types of Loops in PHP

Loops are used to execute the same block of code again and again, as long as a certain condition is met. The basic idea behind a loop is to automate the repetitive tasks within a program to save time and effort. PHP supports four different types of loops.

  • while — loops through a block of code as long as the condition specified evaluates to true.
  • do…while — the block of code executed once and then the condition is evaluated. If the condition is true the statement is repeated as long as the specified condition is true.
  • for — loops through a block of code until the counter reaches a specified number.
  • foreach — loops through a block of code for each element in an array.

 

PHP while Loop

The while statement will loops through a block of code as long as the condition specified in the while statement evaluates to true.

while(condition){
// Code to be executed

}

while loop

PHP do…while Loop

The do-while loop is a variant of the while loop, which evaluates the condition at the end of each loop iteration. With a do-while loop, the block of code executed once, and then the condition is evaluated, if the condition is true, the statement is repeated as long as the specified condition evaluated to is true.

do{
    // Code to be executed

}

while(condition);

do while loop

PHP for Loop

The for loop repeats a block of code as long as a certain condition is met. It is typically used to execute a block of code a certain number of times.

for(initialization; condition; increment){

// Code to be executed

}

for loop

PHP foreach Loop

The foreach loop is used to iterate over arrays.

foreach($array as $value){

// Code to be executed

}

foreach loop

There is one more syntax foreach loop, which is extension of the first.

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

//Code to be executed

}

foreach loop

If you liked our content Types of Loops in PHP, then you may also like PHP Conditional Statements

Be the first to comment

Leave a Reply

Your email address will not be published.


*