Previous | Home | Next |
Looping Statement
If some task is used in the script repeatedly in php there is a need of Looping Statement until a certain condition met.
Types of Looping Statement:
The following Looping Statements support by PHP
- while Statement
- do....while Statement
- for Statement
- foreach Statement
while Loop statement runs the same block of code repeatedly until a condition met.
Syntax:while(condition) { block of code to be executed; }
Example:
<html> <head> <title>while Loop in PHP</title> </head> <body> <?php $A=0; while($A<=15) { echo "$A<br/>"; $A++; } ?> </body> </html>
Output:
do....while Statement is works as while loop. It runs the block of code atleast once after that runs depending upon the condition.
Syntax:Example:
<html> <head> <title>do....while Loop in PHP</title> </head> <body> <?php $A=0; do { echo "$A<br/>"; $A++; }while($A<15) ?> </body> </html>
Output:
for statement is used when you know how many times you want to execute a statement or a block of statements. And everything is defined in single line.
Syntax:for(initialization; condition; increment/decrement) { block of code to be executed; }
Example:
<html> <head> <title>for Loop in PHP</title> </head> <body> <?php $total = 0; for ( $x = 1; $x <= 10; $x++) { $total = $total + $x; } echo "The total sum: ".$total."<br />"; ?> </body> </html>
Output:
foreach loop works on arrays, and is used to loop through each key/value pair in an array.
Syntax:foreach(array as value) { block of code to be executed; }
Example
<html> <head> <title>foreach Loop in PHP</title> </head> <body> <?php $dress = array("sarees", "lehengas", "gowns", "skirts"); foreach ($dress as $value) { echo "$value <br>"; } ?> </body> </html>
Output:
Previous | Home | Next |