PHP Loop: For, While, Do While, Foreach

Use of loop in PHP

Loops in PHP are used to execute the same block of code a specified number of times.

OR

When you want to execute similar statements again and again than place of multiple line script you can use loop.

Four types of Loop used in PHP :

1.For :

  • In for loop specified condition is predefined.
  • When you in advance, how many times you want to execute this times.

2while :

  • while loop executes the statement while a specified condition is true.  In while loop first check the condition then execute the statement.
  • when you don’t know in advance how many times you want to executes this times, statement depend on the condition.
  • condition before execute the statement.

3. Do-while :

  • do – while loop executes the statement once and next statement depends upon a specified condition is true.
  • In do – while loop first execute the statement then check the condition, it means if condition is false in that case one time statement execute.

4. Foreach :

  • Foreach loop executes the statement() of an associative array value.

PHP for Loop

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

The parameters of For loop have following meanings:

  • initialization — it is used to initialize the counter variables, and evaluated once unconditionally before the first execution of the body of the loop.
  • condition — in the beginning of each iteration, condition is evaluated. If it evaluates to true, the loop continues and the nested statements are executed. If it evaluates to false , the execution of the loop ends.
  • increment — it updates the loop counter with a new value. It is evaluate at the end of each iteration.

The example below defines a loop that starts with $i=1. The loop will continued until $i is less than, or equal to 5. The variable $i will increase by 1 each time the loop runs:

Output:

 

PHP while Loop

The While statement will loops through a block of code until the condition in the While statement evaluate to true.

The example below define a loop that starts with $i=1. The loop will continue to run as long as $i is less than or equal to 3. The $i will increase by 1 each time the loop runs:

Output:

Leave a Reply

Your email address will not be published.