Why need loops.
Often when you write php code, you want the same block of code to run over and over again a certain number of times.
So, instead of adding several almost equal code-lines in a script, we can use loops.
Loops are used to execute the same block of code again and again
And there have four types of php codes such as,
- While.
- Do-while.
- For.
- Foreach.
While loop.
$x = 1;
while($x <= 5) {
echo "The number is: $x <br>";
$x++;
- $x = 1; – Initialize the loop counter and set the start value to 1
- $x <= 5 – Continue the loop as long and less than or equal to 5
- $x++; – Increase the loop counter value by 1 for each iteration
Do-while loop.
<?php
$x = 1;
do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 5);
?>
The example below first sets a variable $x to 1 ($x = 1).
Then, the do while loop will write some output
and then increment the variable $x with 1.
Then the condition is checked (is $x less than, or equal to 5?).
and the loop will continue to run as long as $x is less than, or equal to 5.
for loop.
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
- nit counter: Initialize the loop counter value
- test counter: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it evaluates to FALSE, the loop ends.
- increment counter: Increases the loop counter value.
- $x = 0; – Initialize the loop counter ($x), and set the start value to 0
- $x <= 10; – Continue the loop as long as $x is less than or equal to 10
$x++ – Increase the loop counter value by 1 for each iteration.
Foreach loop.
for ($x = 0; $x < 10; $x++) {
if ($x == 4) {
break;
}
The break
statement can also be used to jump out of a loop.
Continue statements.
for ($x = 0; $x < 10; $x++) {
if ($x == 4) {
continue;
}
The continue
statement breaks one iteration.