PHP: Loop Types For, Do.. While, Foreach Available In PHP

The for statement is used when you know how many times you want to execute a statement or a block of statements.

Parameters:

  • init counter: Initialize the loop counter value
  • Test counter: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it evaluates to FALSE, the loop ends.
  • Increment counter: Increases the loop counter value

The example below displays the numbers from 0 to 10:

Syntax

Example

Output :-

The number is: 0
The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5
The number is: 6
The number is: 7
The number is: 8
The number is: 9
The number is: 10

While Loop Statement

The while statement will execute a block of code as long as the specified condition is true.

If the test expression is true, then the code block will be executed. After the code has executed the test expression will again be evaluated and the loop will continue until the test expression is found to be false.

Syntax

Example

Do – While Loop Statement

Do while loop will always execute the block of code once, it will then check the condition, and repeat the loop while the specified condition is true.

Syntax

Example

Output:

The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5

PHP Foreach Loop

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

Syntax

Example

Output:

red
green
blue
yellow

break statement

The PHP break keyword is used to terminate the execution of a loop prematurely.

Example

In the following example condition test becomes true when the counter value reaches 3 and loop terminates.

This will produce the following result −

The continue statement

The PHP continue keyword is used to halt the current iteration of a loop but it does not terminate the loop.

Example

In the following example loop prints the value of array but for which condition becomes true it just skip the code and next value is printed.

This will produce the following result −

Thanks for reading my article about “PHP: Loop Types For, Do.. While, Foreach Available In PHP”. If you like this article do me favor by sharing it with your friends.

Digital Technology Hub