PHP Break

0
2K

The break statement can be used to jump out of different kind of loops.


Break in For loop

The break statement can be used to jump out of a for loop.

ExampleGet your own PHP Server

Jump out of the loop when $x is 4:

for ($x = 0; $x < 10; $x++) {
  if ($x == 4) {
    break;
  }
  echo "The number is: $x <br>";
}
Try it Yourself »

Break in While Loop

The break statement can be used to jump out of a while loop.

Break Example

$x = 0;

while($x < 10) {
  if ($x == 4) {
    break;
  }
  echo "The number is: $x <br>";
  $x++;
}
Try it Yourself »


Break in Do While Loop

The break statement can be used to jump out of a do...while loop.

Example

Stop the loop when $i is 3:

$i = 1;

do {
  if ($i == 3) break;
  echo $i;
  $i++;
} while ($i < 6);
Try it Yourself »

Break in For Each Loop

The break statement can be used to jump out of a foreach loop.

Example

Stop the loop if $x is "blue":

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

foreach ($colors as $x) {
  if ($x == "blue") break;
  echo "$x <br>";
}
Try it Yourself »
Search
Categories
Read More
Other
PHP Nested if Statement
Nested If You can have if statements inside if statements, this is...
By PHP Tutorial 2024-05-17 07:47:26 0 2K
Other
PHP Create Arrays
Create Array You can create arrays by using the array() function: ExampleGet your...
By PHP Tutorial 2024-05-17 08:01:55 0 3K
Other
PHP Associative Arrays
PHP Associative Arrays Associative arrays are arrays that use named keys that you assign to...
By PHP Tutorial 2024-05-17 08:01:14 0 4K
Other
PHP Shorthand if Statements
Short Hand If To write shorter code, you can write if statements on one line....
By PHP Tutorial 2024-05-17 07:47:03 0 2K
Other
PHP if Operators
Comparison Operators If statements usually contain conditions that compare two values....
By PHP Tutorial 2024-05-17 07:45:46 0 2K