PHP- Loops

Loops execute a set of statements repeatedly till the condition get false.

Note: Loops are mainly do two things that are checking the condition and executing the code which is present inside  loops. Based on the order of code execution process and condition checking process, the loops are divided into two categories:  entry controlled loop and exit controlled loop.

  • Entry controlled loops first check the condition, if condition is true then the statement inside the loop is executed.
  • Exit controlled loops first execute loop and then it check the condition is true or false. if it returns true then again execute the program.

The main loops which are used in php programming are listed and described below

  • while
  • do…while
  • for
  • foreach

 

while

In while loop first check the condition, if condition is true then go to execute the program and if the condition is false then exit from the while loop, that is program will be repeatedly executed  until the condition become false. So that the while is an entry controlled loop.

Syntax [ while ]

 

Example 1 [ while ]

Output

 

do…while

In do…while loop first execute the program and then check the condition is true or false. if the condition is true then again execute the program. The process will be repeated until the condition returns a false value. So do…while loop is the one and only exit controlled loop in php.

Syntax [ do…while ]

 

Example 1 [ do…while ]

Output

 

for

For loop execute the program in a given amount of time which is specified in the for loop.

Parameters used in the for loop are given below

  1. Initialization : Initialization of variable. eg: $i=0
  2. Condition : Condition used to make decision. If condition is true then execute program. If condition is false then end the loop. eg : $i<=10
  3. Increment/Decrement: Increment is used to increment the count variable and decrement is used to decrement the count variable. eg:  Increment :- $i++  , Decrement :- $i--

For loops started from intialization and executed repeatedly till the condition get false.

Syntax [ for ]

 

Example 1 [ for ]

Output

 

foreach

  • Foreach loop is used to read array elements.
  • Foreach condition execute all key or value which are used in the array.
  • Exit from the loop only after read all elements of the array.

Syntax [ foreach – Indexed Array without key ]

Syntax [ foreach – Array with key and value ] 

 

Example 1 [ foreach – Indexed Array without key]

Output

 

Example 1 [ foreach – Array with key and value]

Output

 

Summary
PHP- Loops
Article Name
PHP- Loops
Description
PHP Loops. 2 types of loop : Entry Controlled and Exit Controlled. Tutorial about while, do..while, foreach, for.
Author
Publisher Name
Jees K Denny
Publisher Logo

Leave a Reply