EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login

Break in PHP

Home » Software Development » Software Development Tutorials » PHP Tutorial » Break in PHP

Break in PHP

Introduction to Break Statement in PHP

PHP break statement is used to exit from a loop instantaneously without having to wait for getting back at the conditional statements like for loop, while loop, do-while, switch and for-each loop. If there are multiple loops present and the break statement is used, it exits only from the first inner loop. Break is present inside the statement block and gives the user full freedom to come out of the loop whenever required.

Syntax:

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

<?php
//variable declarations
//conditional statement block
{
break;
}
?>

Flowchart:

Break in PHP Flowchart

As shown above, the code first enters the conditional statement block once the condition for the loop is satisfied and continuously executes the statements in the loop until the condition is not satisfied. When a break statement is written in the code, as soon as the program encounters it the code exits from the current loop irrespective of whether the condition is satisfied or not as shown.

Examples of Break in PHP

Let us understand the working of a break statement by taking a few examples for each conditional statement in various scenarios and checking its behavior for the same.

Example #1

Break statement inside the “for” loop.

Code:

<?php
$var = 1;
for ($var = 0;$var <= 10;$var++)
{
if ($var==5)
{
break;
}
echo $var;
echo "\n";
}
echo "For loop ends here" ;
?>

Output:

Break in PHP eg1

Here we are printing the numbers from 1 to 10 in the for loop by initializing 1 to variable “var”. “var” starts printing incremental numbers starting from 1 till it encounters the if loop condition. Here we are mentioning that the variable should come out of the loop once its value reaches 5. This is done using the break statement as shown. We can see the same in the output as we are printing “For loop ends here” once the break statement is executed and it comes out of for loop even if for loop condition is not satisfied. Hence the break statement comes out of the entire logic of all other iterations.

Example #2

This example is to check the functionality of the break statement in a while loop.

Code:

<?php
$var = 0;
while( $var < 10) {
$var++;
if( $var == 5 )break;
echo ("Current variable value = $var");
echo "\n";
}
echo ("Exited loop at variable value = $var" );
?>

Output:

Break in PHP eg2

In the above program variable “var” is first initialized to 0 and using while loop we are incrementing its value by one and printing the same. We are writing an if condition wherein we are making the code to exit by using a break statement once the variable value equals 5. This break makes it exit from the current while loop even though the specified condition of incrementing variable until the value 10 is not met. We are displaying the variable value at which the loop is broken.

Popular Course in this category
PHP Training (5 Courses, 3 Project)5 Online Courses | 3 Hands-on Project | 28+ Hours | Verifiable Certificate of Completion | Lifetime Access
4.5 (5,726 ratings)
Course Price

View Course

Related Courses
Java Servlet Training (6 Courses, 12 Projects)All in One Software Development Bundle (600+ Courses, 50+ projects)

Example #3

Here we are implementing break statements in the foreach loop.

Code:

<?php
$array = array('A', 'B', 'C', 'D', 'E', 'F');
foreach ($array as $let) {
if ($let == 'E') {
break;
}
echo "$let \n";
}

Output:

Break in PHP eg3

In this program, we are first declaring an array containing a collection of letters. Then by using a foreach loop, we are printing all the elements of the array one by one. An if the conditional statement is introduced to break the loop once the value of array pointer reaches the letter “E”. Hence on encountering break statement the code exits without printing the next letter in the array i.e. “F”.

Example #4

The most common application of break is in a switch statement which can be shown below.

Code:

<?php
$a=1;
switch ($a) {
case 0:
echo "a equals 0";
break;
case 1:
echo "a equals 1";
break;
case 2:
echo "a equals 2";
break;
}
?>

Output:

Break in PHP eg4

This is the example of a simple switch statement where we are initializing the variable value to 1 at first. Then by the use of switch conditions, we are checking the variable value and printing it once the condition matches.

Example #5

Here let us see the working of a break statement when there are two or more loops (conditional statements).

Code:

<?php
// PHP program to verify break of inner loop
// Declaration of 2 arrays as below
$array1 = array( 'One', 'Two', 'Three' );
$array2 = array( 'Three', 'One', 'Two', 'Four' );
// Outer foreach loop
foreach ($array1 as $a1) {
echo "$a1 ";
// Inner nested foreach loop
foreach ($array2 as $a2) {
if ($a1 != $a2 )
echo "$a2 ";
else
break 2;
}
echo "\n";
}
echo "\n Loop Terminated";
?>

Output:

eg5

Here we are using 2 nested foreach loops and also showing a case of using “break 2” which breaks out of both the loops in contrast to the “break” statement which breaks out of only the inner loop.

We have declared two arrays array1 and array2 and we are displaying the values of array2 for each value of array1 until and unless the value of array1 is not equal to array2. Once the value in array1 becomes the same as array2 we are breaking both loops by making use of break 2 statement which prevents the code from executing any more statements.

Example #6

Here we shall see how to use break statements to come out of “n” number of loops (conditional statements).

Code:

<?php
## Outermost first for loop
for($a=1;$a<5;$a++){
echo ("Value of a is = $a");
echo "\n";
## Second for loop
for($b=1;$b<3;$b++){
echo ("Value of b is = $b");
echo "\n";
## Third for loop
for($c=2;$c<3;$c++){
echo ("Value of c is = $c");
echo "\n";
## Fourth for loop
for($d=2;$d<4;$d++){
echo ("Value of d is = $d");
echo "\n";
if( $a == 3 ){
break 4;
}
}
}
}
}
echo 'Loop has terminated and value of a = '.$a;
?>

Output:

 eg6

The break statement followed by the number of loops that need to be exited from are used to terminate from “n” number of loops.

Syntax:

break n;

where n is the number of loops that need to be exited from the loop.

We are using 4 nested for loops for this purpose. Variables a, b, c, d is initialized respectively for each for loop and we are incrementing their values by 1. The same values are displayed in the output to understand its flow better. At last, we are giving a condition for all the 4 loops to break if the value of the first variable becomes equal to 3 which it eventually did and can be shown in the output. We are printing the loop has terminated at the end along with as value to note the break’s functionality.

Conclusion

When we are using one or more conditional statements in our code and we need to exit from the same at a particular point, we can use the break statement. Basically, it helps to terminate from the code when the condition we give falls TRUE. We can also pass an integer along with break to terminate from any number of existing loops instead of declaring the break again and again.

Recommended Articles

This is a guide to Break in PHP. Here we discuss the introduction and top 6 examples of break in PHP using different conditions along with its implementation. You may also look at the following articles to learn more-

  1. PHP Filters
  2. PHP File Handling
  3. Multidimensional Array in PHP
  4. Random Number Generator in PHP

PHP Training (5 Courses, 3 Project)

5 Online Courses

3 Hands-on Project

28+ Hours

Verifiable Certificate of Completion

Lifetime Access

Learn More

0 Shares
Share
Tweet
Share
Primary Sidebar
PHP Tutorial
  • Control Statements
    • Control Statement in PHP
    • PHP if Statement
    • if else Statement in PHP
    • elseif in PHP
    • PHP Switch Statement
    • Continue in PHP
    • Break in PHP
  • PHP Basic
    • Introduction To PHP
    • What is PHP
    • PHP Keywords
    • Advantages of PHP
    • Career In PHP
    • Comments in PHP
    • PHP Commands
    • PHP Frameworks
    • PHP Compiler
    • Variables in PHP
    • PHP Superglobal Variables
    • PHP Versions
    • Object in PHP
    • What is Drupal
    • Top PHP Frameworks
    • WebStorm IDE
    • What is phpMyAdmin?
    • PhpStorm
    • Install phpMyAdmin
    • Phalcon Model
  • Data Types
    • PHP Data Types
    • PHP Integer
    • PHP Booleans
  • Operators
    • PHP Operators
    • Arithmetic Operators in PHP
    • Comparison Operators in PHP
    • Logical Operators in PHP
    • Bitwise Operators in PHP
    • Ternary Operator in PHP
    • PHP String Operators
  • Loops
    • PHP Loops
    • For Loop in PHP
    • PHP Do While Loop
    • PHP While Loop
    • While Loop in PHP
    • Foreach Loop in PHP
  • Constructor
    • Constructor in PHP
    • Destructor in PHP
  • State Management
    • Cookie in PHP
    • Sessions in PHP
  • Array
    • What is PHP Array
    • Arrays in PHP
    • 2D Arrays in PHP
    • Associative Array in PHP 
    • Multidimensional Array in PHP
    • Indexed Array in PHP
    • PHP Array Functions
    • PHP unset Array
    • PHP Append Array
    • PHP Array Search
    • PHP Split Array
    • PHP array_push()
    • PHP array_pop()
  • Functions
    • Functions in PHP
    • PHP Math Functions
    • PHP Recursive Function
    • PHP String Functions
    • Hashing Function in PHP
    • Date Function in PHP
    • PHP Anonymous Function
    • Calendar in PHP
    • PHP Call Function
    • PHP Pass by Reference
    • PHP ucfirst()
    • PHP ucwords()
    • trim() in PHP
    • isset() Function in PHP
    • PHP replace
    • PHP fpm
    • PHP strpos
    • preg_match in PHP
    • PHP preg_replace()
    • PHP ob_start()
    • PHP Reflection
    • PHP Split String
    • PHP URL
    • PHP preg_match_all
    • PHP strtoupper()
    • PHP preg_split()
    • PHP substr_replace()
    • PHP setlocale()
    • PHP substr_count()
    • PHP Serialize
    • PHP strlen()
    • PHP async
    • PHP Date Time Functions
    • PHP timezone
    • PHP Data Object
    • print_r() in PHP
    • PHP header()
    • PHP strip_tags()
    • PHP chop()
    • PHP MD5()
    • PHP unset()
    • PHP crypt()
    • PHP wordwrap()
    • PHP is_null()
    • PHP strtok()
    • PHP bin2hex()
    • PHP parse_str()
    • PHP levenshtein()
    • PHP addslashes()
    • PHP strtotime
    • PHP sha1()
    • PHP explode()
    • PHP sscanf()
    • PHP require_once
    • PHP Zip Files
    • PHP $_SERVER
    • PHP $_POST
    • PHP Include and Require
    • PHP POST Method
  • Advanced
    • Overloading in PHP
    • Overriding in PHP
    • Method Overloading in PHP
    • Inheritance in PHP
    • Multiple Inheritance in PHP
    • PHP Interface
    • Encapsulation in PHP
    • PHP Constants
    • PHP Magic Constants
    • PHP Regular Expressions
    • PHP GET Method
    • PHP Annotations
    • PHP Encryption
    • PHP file Functions
    • PHP readfile
    • PHP?Write File
    • PHP Append File
    • PHP Type Hinting
    • PHP Filters
    • PHP Float
    • PHP Form
    • PHP Form Validation
    • Sorting in PHP
    • PHP usort()
    • PHP Stack Trace
    • PHP Stack Overflow
    • PHP Pagination
    • PHP implode
    • Polymorphism in PHP
    • Abstract Class in PHP
    • PHP Final Class
    • PHP Custom Exception
    • error_reporting() in PHP
    • PHP Log Errors
    • Access Modifiers in PHP
    • PHP Change Date Format
    • Static Method in PHP
    • PHP File Handling
    • PHP Output Buffering
    • Get IP Address in PHP
    • Upload a File in PHP
    • String in PHP
    • Public Function in PHP
    • Private in PHP
    • Protected in PHP
    • basename in PHP
    • Validation in PHP
    • PHP mail()
    • PHP Email Form
    • PHP Directory
    • PHP Create Session
    • PHP include_once
    • PHP json_decode
    • PHP XMLWriter
    • PHP XML Reader
    • PHP XML Parser
    • PHP XML into Array
    • Phalcon Framework
  • Programs
    • Patterns in PHP
    • Star Patterns in PHP
    • Swapping in PHP
    • Fibonacci Series PHP
    • Factorial in PHP
    • Reverse String in PHP
    • Square Root in PHP
    • Random Number Generator in PHP
    • Palindrome in PHP
    • Prime Numbers in PHP
    • Armstrong Number in PHP
    • Socket Programming in PHP
    • Login Page in PHP
    • PHP Login Template
    • PHP Object to String
  • Database
    • PHP Database Connection
    • How to Connect Database to PHP
  • Interview Questions
    • PHP Interview Questions
    • PHP OOP Interview Questions
    • CakePHP Interview Questions
    • Core PHP Interview Questions

Related Courses

PHP Training Course

Java Servlet Training

Software Development Course Training

Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

© 2020 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you
Book Your One Instructor : One Learner Free Class

Let’s Get Started

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA Login

Forgot Password?

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

Special Offer - PHP Training (5 Courses, 3 Project) Learn More