PHP Loops - Codingque

PHP Loops

Understand how to use different types of loops in PHP with examples and explanations.

Introduction to Loops

Loops in PHP are used to execute a block of code repeatedly based on a condition. There are several types of loops in PHP:

1. for Loop

The for loop is used when the number of iterations is known beforehand. It consists of an initialization, condition, and increment/decrement expression.

<?php
for ($i = 0; $i < 5; $i++) {
    echo "Iteration: $i<br>";
}
?>

Explanation: The for loop initializes the variable $i to 0. It continues looping while $i is less than 5, and increments $i by 1 in each iteration. The output will display "Iteration: 0" through "Iteration: 4".

2. while Loop

The while loop is used when the number of iterations is not known and is determined by a condition. The loop runs as long as the condition evaluates to true.

<?php
$i = 0;
while ($i < 5) {
    echo "Iteration: $i<br>";
    $i++;
}
?>

Explanation: The while loop checks the condition $i < 5 before each iteration. If true, it executes the code block and then increments $i. The loop continues until $i is no longer less than 5.

3. do-while Loop

The do-while loop is similar to the while loop, but it guarantees that the code block will execute at least once before checking the condition.

<?php
$i = 0;
do {
    echo "Iteration: $i<br>";
    $i++;
} while ($i < 5);
?>

Explanation: The do-while loop executes the code block first, then checks the condition $i < 5. If the condition is true, it continues to the next iteration. The loop ensures that the code block runs at least once.

4. foreach Loop

The foreach loop is used to iterate over arrays. It simplifies the process of iterating through each element in an array.

<?php
$fruits = array("Apple", "Banana", "Cherry");

foreach ($fruits as $fruit) {
    echo "Fruit: $fruit<br>";
}
?>

Explanation: The foreach loop iterates over each element in the $fruits array. In each iteration, the current value is assigned to the $fruit variable, and the loop prints the value.

Previous Next
Modern Footer