Course Content
About Lesson

What is Loop and How many types of loop?

Loops are used to execute the same block of code repeatedly as long as a condition is true.

PHP supports the following loops:

Loop TypeDescription
whileRepeats as long as the condition is true
do...whileExecutes the code block once, then repeats as long as the condition is true
forLoops through a block of code a specified number of times
foreachLoops through each item in an array

🔁 1. while Loop

Syntax:

while (condition) {
// code to be executed
}

Example:

PHP
<?php
$x = 1;
while ($x <= 5) {
  echo "Number: $x <br>";
  $x++;
}
?>

🔁 2. do...while Loop

Syntax:

do{
// code to be executed
} while (condition);

Example:

PHP
<?php
$x = 1;
do {
  echo "Count: $x <br>";
  $x++;
} while ($x <= 3);
?>

✔ Executes the loop at least once, even if the condition is false.

🔁 3. for Loop

Syntax:

for (initialization; condition; increment) {
// code to be executed
}

Example:

PHP
<?php
for ($i = 1; $i <= 5; $i++) {
  echo "Line $i <br>";
}
?>

🔁 4. foreach Loop (Used for Arrays)

Syntax:

foreach ($array as $value) {
// code to be executed
}

Example:

PHP
<?php
$colors = ["Red", "Green", "Blue"];
foreach ($colors as $color) {
  echo "$color <br>";
}
?>

⚠️ Loop Control Statements

StatementUse
breakStop the loop entirely
continueSkip current iteration and go to the next

Example:

PHP
<?php
for ($i = 1; $i <= 5; $i++) {
  if ($i == 3) {
    continue;  // Skips number 3
  }
  echo "$i <br>";
}
?>