The PHP break statement

A break statement is an intentional interruption that prevents the loop from running. Sometimes a situation arises that makes us want to exit from a loop immediately without waiting to get back to the conditional statement.

The keyword break ends execution of the current for, foreach, while, or do while loops.

When the keyword break is executed inside a loop, the control is automatically passed on to the first statement outside of the loop.

A break is usually associated with the if statement.

Code

In the following example, we test the value of $sum; if it becomes greater than 1300, the break statement terminates the execution of the code. As the echo statement is the first statement outside of the loop, it will print the current value of $sum.

Take a look at the code below:

<?php
$array1=array(100, 1100, 200, 400, 900);
$x1=0;
$sum=0;
while ($x1<=4)
{
if ($sum>1300)
{
break;
}
$sum = $sum+$array1[$x1];
$x1=$x1+1;
}
echo $sum;
echo "\n";
echo "The loop ran ", $x1, " times";
?>

After adding the first three values the sum became 1400, the break statement was executed, and the loop was terminated. This is why the loop only ran three times.

New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved