PHP Loops

In PHP Loops allow you to execute a block of code repeatedly until a certain condition is met. PHP has the following loop types:

  1. while – Executes a block of code as long as a condition is true.
  2. do…while – Executes a block of code, and then repeats the block as long as a condition is true.
  3. for – Executes a block of code for a specified number of times.
  4. foreach – Executes a block of code for each element in an array.

Here is an example of how you can use a ‘while’ loop:

$x = 1;

while ($x <= 10) {
  echo $x . ' ';
  $x++;
}

Here is an example of how you can use a ‘do…while’ loop:

$x = 1;

do {
  echo $x . ' ';
  $x++;
} while ($x <= 10);

Here is an example of how you can use a ‘for’ loop:

for ($x = 1; $x <= 10; $x++) {
  echo $x . ' ';
}

Here is an example of how you can use a ‘foreach’ loop:

$colors = array('red', 'green', 'blue');

foreach ($colors as $color) {
  echo $color . ' ';
}

In PHP, the ‘break’ and ‘continue’ statements can be used to control the flow of a loop.

The ‘break’ statement breaks out of a loop and ‘continue’ executing the code after the loop.

The ‘continue’ statement skips the rest of the current iteration of the loop and ‘continue’ with the next iteration.

Here is an example of how you can use the ‘break’ statement:

for ($x = 1; $x <= 10; $x++) {
  if ($x == 5) {
    break;
  }
  echo $x . ' ';
}

This code will output “1 2 3 4” because the ‘break’ statement breaks out of the loop when

‘$x’ is 5.

Here is an example of how you can use the ‘continue’ statement:

for ($x = 1; $x <= 10; $x++) {
  if ($x % 2 == 0) {
    continue;
  }
  echo $x . ' ';
}