PHP all Loop Example with in-Details
PHP all loop example with Details
- " Using the
for
Loop:"
- The
for
loop is used when you know the number of iterations beforehand. - Syntax:
for (initialization; condition; increment/decrement) {
// Code to be executed
}
- Example:
for ($i = 0; $i < 5; $i++) {
echo "Iteration: $i
";
} - Explanation:
initialization: Sets the initial value of the loop counter variable ($i in this case).
condition: Specifies the condition for the loop to continue executing.
increment/decrement: Modifies the loop counter variable after each iteration.
2." Using the while
Loop:"
- The
while
loop is used when you want to execute a block of code as long as a condition is true. - Syntax:
while (condition) {
// Code to be executed
} - Example:
$i = 0;
while ($i < 5) {
echo "Iteration: $i
";
$i++;
} - Explanation:
The loop continues to execute the code block as long as the condition $i < 5 is true.
Inside the loop, $i is incremented after each iteration to avoid an infinite loop.
3.
" Using the do-while
Loop:"
- The
do-while
loop is similar to thewhile
loop, but it always executes the code block at least once before checking the condition. - Syntax:
do {
// Code to be executed
} while (condition); - Example:
$i = 0;
do {
echo "Iteration: $i
";
$i++;
} while ($i < 5); - Explanation:
The code block is executed once before the condition $i < 5 is checked.
If the condition is true, the loop continues to execute..