What Are Different Types Of Loops With Explanation In PHP

admin_img Posted By Bajarangi soft , Posted On 16-09-2020

Different types of loops in php

Different types of loops in php

 

  • Execute the same block of code again to again, as long as certain condition is met. instead of adding several almost equal code-lines in a script, we can use loops.
We have the following loop types:
  • while loops through a block of code as long as the condition specified evaluates to true
  • do...while - loops through a block of code once, and then repeats the loop as long as the specified condition is true
  • for - loops through a block of code a specified number of times
  • foreach - loops through a block of code for each element in an array

php while loop
  • The while loop executes a block of code as long as the specified condition is true.
  • Example:

       while (condition is true) {
      code to be executed;
   }


php do….While loop
  •  it will then check the condition, and repeat the loop while the specified condition is true.
  • Example:
  •  do {
      code to be executed;
    } while (
    condition is true);

     


PHP for Loop
  • It is typically used to execute a block of code for certain number of times.
  • Example:

             for(initialization; condition; increment){
    // Code to be executed
    }

 

 

PHP foreach Loop

  • The foreach loop works only on arrays, and is used to loop through each key/value pair in an array.
  • Example:

foreach ($array as $value) {
  code to be executed;
}

Related Post