JavaScript Tutorial

Iterative Statements / PHP Loops

Loops are used to execute a set of statements for a certain number of times until the controlling expression is false. PHP loops are as :

  • while Loop
  • do...while Loop
  • for Loop
  • foreach Loop

while Loop

while loop is used to execute a set of statements as long as the testing condition is TRUE.

//syntax: 

while(condition) {
  	statements to execute
}

do...while Loop

do...while loop executes the statements within the block and after that the condition is tested which means even though the condition is unsatisfactory in beginning, still the code inside the loop will run once.

//syntax: 
do{
       statements to execute;
} while(condition);

for Loop

for loop is used to execute a certain set of statements for a specified number of times.

//syntax : 
for (init counter; test counter; increment/decrement counter) {
  	set of statements to execute;
} 

Parameters under for loop:

  1.     init counter : Initialize the variable.
  2.     test counter: At each iteration if the condition evaluates to TRUE, the loop continues else the loop ends.
  3.     increment/decrement counter : Increases or decreases the counter variable

Understanding for Loop example

  • $num = 0 is to initialize the variable ($num)
  • $num <= 10 to continue the loop until $num <= 5 condition is satisfied 
  • $num++ is to update the counter variable for next iteration

foreach Loop

foreach loop is used to traverse each element of an array using a key/value pair in an array. In each iteration, the current value of an array is assigned to $value and then the array pointer is moved by one.

//syntax : 
foreach ($array as $value) {
      statements to execute
} 

break / continue Statement

On encountering a break statement in a loop, loop execution is terminated and the control is passed on to the next statement following the particular loop.

On encountering a continue statement in a loop, the control of the loop jumps towards the next iteration and the statement execution for the current iteration is skipped.

 

Go back to Previous Course