PHP Loops

Loops in PHP are used to repeat a block of code multiple times. They are helpful when you need to perform the same task, like displaying numbers or processing items in an array.

Types of Loops in PHP

1. while Loop

The while loop runs as long as the condition is true.

Syntax:

while (condition) {
    // Code to run
}

Try It Now

Exmple:

<?php
$count = 1;
while ($count <= 5) {
    echo $count . " ";
    $count++;
}

// Output: 1 2 3 4 5
?>

Try It Now

2. do-while Loop

Similar to while, but it always runs at least once, even if the condition is false.

Syntax:

do {
    // Code to run
} while (condition);

Try It Now

Example:

<?php
$count = 1;
do {
    echo $count . " ";
    $count++;
} while ($count <= 5);

// Output: 1 2 3 4 5

?>

Try It Now

3. for Loop

The for loop is used when you know in advance how many times you want to repeat the code.

Syntax:

for (initialization; condition; increment) {
    // Code to run
}

Try It Now

Example:

<?php
for ($i = 1; $i <= 5; $i++) {
    echo $i . " ";
}

// Output: 1 2 3 4 5

?>

Try It Now

4. foreach Loop

The foreach loop is specifically used to iterate through arrays.

Syntax:

foreach ($array as $value) {
    // Code to run
}

Try It Now

Example:

<?php
$colors = array("Red", "Green", "Blue");
foreach ($colors as $color) {
    echo $color . " ";
}

// Output: Red Green Blue

?>

Try It Now

Key Points

  1. while: Use when the number of repetitions depends on a condition.
  2. do-while: Similar to while but runs at least once.
  3. for: Best when you know how many times to loop.
  4. foreach: Perfect for arrays or lists.