Loops in PHP are used to create the same block of code a certain number of times. PHP supports four loop types.
- for - loops through the code block a certain number of times.
- while - encapsulates with a code block if and as long as the stated condition is true.
- do ... while - wrap up the code block once, and repeat the loop as long as the condition is true.
- foreach - a loop with a code block for each item in sequence.
The for loop statement
The for statement is used when you know how often you want to execute a statement or a block of statements.
Syntax
for (initialization; condition; increment){
code to be executed;
}
- "for…{…}" is the loop block
- "initialize" usually an integer; it is used to set the counter’s initial value.
- "condition" the condition that is evaluated for each php execution. If it evaluates to true then execution of the for... loop is terminated. If it evaluates to false, the execution of the for... loop continues.
- "increment" is used to increment the initial value of counter integer.
The code below uses the “for… loop” to print values of multiplying 10 by 0 through to 10
#example.php
<?php
for ($i = 0; $i < 10; $i++) {
$product = 10 * $i;
echo "The product of 10 * $i is $product ";
}
?>
Output:
The product of 10 x 0 is 0
The product of 10 x 1 is 10 The product of 10 x 2 is 20 The product of 10 x 3 is 30 The product of 10 x 4 is 40 The product of 10 x 5 is 50 The product of 10 x 6 is 60 The product of 10 x 7 is 70 The product of 10 x 8 is 80 The product of 10 x 9 is 90 |
The while loop statement
A statement while we will use the code block if and as long as the condition statement is true
Syntax
while (condition) {
code to be executed;
}
- "while(…){…}" is the while loop block code
- "condition" is the condition to be evaluated by the while loop
- "block of code…" is the code to be executed if the condition gets true
Example
This example decrements a variable value on each iteration of the loop and the counter increments until it reaches 10 when the evaluation is false and the loop ends.
#text.php
<?php
$i = 0;
$num = 50;
while ($i < 10) {
$num--;
$i++;
}
echo ("Loop stopped at i = $i and num = $num" );
?>
output:
Loop stopped at i = 10 and num = 40 |
The do...while loop statement
The statement of do ... while will execute the code block at least once - then will repeat the loop as long as the situation is true.
Syntax
do {
code to be executed;
}
while (condition);
- "do{…} while(…)" is the do… while loop block code
- "condition" is the condition to be evaluated by the while loop
- "block of code…" is the code that is executed at least once by the do… while loop
Example
The following example will increase the value of i at least once, and will continue to increase the variable i as long as it has a value less than 10 -
test.php
<?php
$i = 0;
$num = 0;
do {
$i++;
} while ($i < 10);
echo ("Loop stopped at i = $i" );
?>
output:
Loop stopped at i = 10 |