Looping Statement In PHP

656 0

Loops execute a block of code a specified number of time, or while a specified condition is true.

In PHP , the following looping statements are used

  • The while Loop
  • The Do …while Loop
  • The For Loop
  • The Foreach Loop
  • Break and Continue Statement

The While Loop
While structure is the another type of loop statement, where the condition is checked at first, the iteration will not stop even if the value changes while executing Statements.
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

The Do While Loop
Do while statement is same as the while statement, the only difference is that it evaluates the expression at the end.
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

The For Loop
The for loop is used when you know in advance how many times the script should run.
Syntax-

The for loop statement take three expressions inside its parenthesis. Separated by semi-colons. When the for loop executes, the following occurs –

  • The initialization expression is executed. This expression usually initializes one or more loop counter, but the syntax allows an expression of any degree of complexity.
  • The Condition expression is evaluated. If the value of condition is true, the loop statement execute. If the value of condition is false, the for loop terminates.
  • The update expression increment executes.
  • The statement executes, and control return to step 2.

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

The Foreach Loop
For Each structure is a loop structure used for arrays.
Syntax –

Example-

Output-
Processing info@phpgurukul.com
Processing anuj.lpu1@gmail.com

The Break Statement
Break end the execution of the for , for each , do-while or switch statement.
Syntax-

Example- 

Output- 
At 5;
At 10;quitting

The Continue Statement
“Continue” is used to skip the current loop iteration and continue with the next iteration of the loop. But “Break” is used to exist from the whole loop.
Syntax –

Example –

Output – 0 1 2 3 4 6 7 8 9 10

Comments

comments

In this article

Join the Conversation