PHP Loop Types

In PHP, there are four main types of loops:

  1. for loop: This loop executes a block of code for a specific number of times. It requires an initialization statement, a condition statement, and an increment/decrement statement.

Example:

for ($i = 0; $i < 10; $i++) {
    echo $i;
}
  1. while loop: This loop executes a block of code while a specified condition is true.

Example:

e$i = 0;
while ($i < 10) {
    echo $i;
    $i++;
}
  1. do-while loop: This loop executes a block of code at least once, and then continues to execute the block while a specified condition is true.

Example:

$i = 0;
do {
    echo $i;
    $i++;
} while ($i < 10);
  1. foreach loop: This loop is used specifically for arrays and objects. It iterates over each element in the array/object and executes a block of code for each element.

Example:

$colors = array("red", "green", "blue");
foreach ($colors as $color) {
    echo $color;
}

You may also like...

Popular Posts

Leave a Reply

Your email address will not be published. Required fields are marked *