HOME HTML EDITOR C JAVA PHP

PHP Loops

Loops are used to execute the same block of code again and again, as long as a certain condition is true. This saves you from writing the same code multiple times.

1. The while Loop

The while loop loops through a block of code as long as the specified condition is true.

<?php
  $x = 1;

  while($x <= 5) {
    echo "The number is: $x <br>";
    $x++;
  }
?>

2. The do...while Loop

The do...while loop will always execute the code block once, then check the condition, and repeat the loop as long as the condition is true.

<?php
  $x = 1;

  do {
    echo "The number is: $x <br>";
    $x++;
  } while ($x <= 5);
?>

3. The for Loop

The for loop is used when you know in advance how many times the script should run.

<?php
  for ($x = 0; $x <= 10; $x++) {
    echo "The number is: $x <br>";
  }
?>

4. The foreach Loop

The foreach loop works only on arrays and is used to loop through each key/value pair in an array.

<?php
  $colors = array("red", "green", "blue", "yellow");

  foreach ($colors as $value) {
    echo "$value <br>";
  }
?>

5. Break and Continue

The break statement is used to jump out of a loop. The continue statement breaks one iteration (in the loop) if a specified condition occurs, and continues with the next iteration in the loop.

<?php
  for ($x = 0; $x < 10; $x++) {
    if ($x == 4) {
      break; // Stops the loop at 4
    }
    echo "Number: $x <br>";
  }
?>
Important: Always remember to increment your counter (like $x++) in a while loop, otherwise you will create an infinite loop that will crash your browser or server!