Loops · Lesson 5 of 6
break
Exit a loop early when its stopping condition is reached.
Lesson
break exits the nearest loop immediately. Use it for a clear early-stop condition, such as finding the first matching item. If several nested loops need to stop together, refactor into a function or use a deliberate loop level rather than obscuring control flow.
This search stops once the requested value is found.
Further guidance
Before running a loop, identify the value that changes and the condition that eventually stops it. Check empty collections and one-item collections as well as the normal case. Prefer foreach when iterating a collection, and keep early exits easy to understand.
Practice task: Create a fresh example for break. Predict the result before running it, then change one input and explain why the result changes. Test a normal case and one boundary or invalid case where it applies. Compare your output with the example and note one rule you would use in a real project.
Code examples
break
PHP
foreach ([4, 8, 12, 16] as $value) {
if ($value === 12) {
echo $value;
break;
}
}
Expected output
12
Key points
- Exit a loop early when its stopping condition is reached.
- Identify the loop state and a clear termination condition.
- Test empty and one-item inputs as well as the normal case.
Your learning progress
Finish this lesson
Optional practice
PHP playground
This site does not execute learner-provided PHP code. Connect a secured PHP sandbox service before enabling code execution.
Execution is disabled. No code is sent to a server.