PHP Loops

In PHP, loops are used to execute a block of code repeatedly under certain conditions. PHP supports several types of loops:


1. for Loop

Used when the number of iterations is known.

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

2. while Loop

Executes as long as a specified condition is true.

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

3. do...while Loop

Executes the code block once, then repeats as long as the condition is true.

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

4. foreach Loop

Used to loop through arrays.

$colors = ["red", "green", "blue"]; foreach ($colors as $color) { echo "$color <br>"; }

For associative arrays:

$person = ["name" => "John", "age" => 30]; foreach ($person as $key => $value) { echo "$key: $value <br>"; }