<<

PHP Looping Statements Looping statements are used to control repetition in a program. It allows a programmer to execute one or more lines of code repetitively. PHP supports following four loop types: i) while ii) do…while iii) for iv) foreach i) The most loop in PHP is the while loop. The purpose of a while loop is to execute a statement or code block repeatedly as long as specified condition is true. Once the specified condition becomes false, the loop will be exited.

Syntax of while loop is: while(condition) { code block to be executed } Example: while loop "; $i++; } ?>

After the execution of above code, the output would be look like:

ii) The do while loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true or false, and then it will repeat the loop as long as the condition is true. Syntax of do while loop is: do { code block to be executed } while (condition); Example: do while loop "; $i++; } while($i<=5); ?>

After the execution of above code, the output would be look like:

iii) The for loop is the most compact form of looping and includes the following three important parts:  The loop initialization statement where we initialize our counter to a starting value. The initialization statement is executed before the loop begins.  The test statement which will test if the given condition is true or not. If condition is true then code given inside the loop will be executed otherwise loop will come out.  The iteration statement where you can increase or decrease your counter. You can put all the three parts in a single line separated by a semicolon. Syntax of for loop is: for(initialization statement; test statement; iteration statement) { the code block to be executed } Example: for loop "; } ?>

After the execution of above code, the output would be look like:

iv) The foreach loop works only on arrays. For every loop iteration, the value of the current array element is assigned to $value and the array pointer is moved by one, until it reaches the last array element.

Syntax of foreach loop is: foreach ($array as $value) { code to be executed; }

Example: foreach loop "; } ?>

After the execution of above code, the output would be look like: