The four type of loop statements are supported by PHP. They are:
- while
- do-while
- for
- foreach
while loop
while loop executes the block of code until the condition or expression return false.
Syntax:
1 2 3 |
while(condition) { php code } |
If the condition is TRUE then the PHP code inside the block will be executed.
Example
1 2 3 4 5 6 7 8 |
<?php $i = 1; while($i <= 5) { echo $i . "<br />"; $i++; } ?> |
In the above example, we have declared PHP variable $i
. Every time the while loop will check if the given condition $i <= 10
is TRUE or Not.
If the condition is TRUE then inside the block, the PHP code echo $i . "<br />"; $i++;
will be executed. echo
is used to print the variable in the browser. And <br />
is used for line breaks to be visible in the browser.
Click the below button to see the demo of above example.
Demo
do-while loop
do-while loop is same like while loop, the differentiation is that do-while evaluate the condition at the end of every loop, whereas while loop checks the condition at first.
Syntax:
1 2 3 |
do { php code } while(condition); |
Example
1 2 3 4 5 6 7 8 9 |
<?php $i = 1; do { echo $i . "<br />"; $i++; } while($i <= 5); ?> |
Click the below button to see the demo of above example.
Demo
for loop
for loop in PHP is same as C language. Every for loop should have three expressions, first one is for declaration, second one is for to check the condition and third expression is for increment or decrement the declare_variable.
Syntax:
1 2 3 |
for(declare_variable;conditional_expression;increment_or_decrement) { php code } |
Example
1 2 3 4 5 6 7 |
<?php for ($i = 1; $i<= 5; $i++) { echo $i . "<br />"; } ?> |
Click the below button to see the demo of above example.
Demo
foreach loop
The foreach loop is used to iterate arrays and objects. In the first iteration first array element will be placed and the loop will last until all elements will be placed.
Syntax:
1 2 3 |
foreach($array as $key => $value) { php code } |
Example
1 2 3 4 5 6 7 8 |
<?php $array = array(1, 2, 3, 4, 5); foreach($array as $key => $value) { echo "key = $key and value = $value <br />"; } ?> |
Instead of "$key => $value" we can use "$value" like foreach($array as $value)
if we don't want the $key
value.
Click the below button to see the demo of above example.
Demo
we can re-write the above example as following, both will provide the same output.
Example
1 2 3 4 5 6 7 8 |
<?php $array = array(1, 2, 3, 4, 5); foreach($array as $key => $value) { echo 'key = ' . $key . ' and value = ' . $value . ' <br />'; } ?> |
Click the below button to see the demo of above example.
Demo