Die, Exit and Break in PHP

Die and Exit

These two constructs are equivalent with each other. They are used to stop the execution of the current PHP script. A message can also be printed as well. These are used when there is an error in a script and you want to exit it as soon as a problem is encountered. Like when you try to open a file and the file doesn’t exist or when you fail to connect to a MySQL database.


If testfile.txt is present, it opens the file for reading and prints the following output:

If testfile.txt is not present, it exits the script and prints the following output:


  • Notice how the upcoming lines are not executed when an error is encountered.
  • The above example works the same when die is replaced with exit.


Break is used to stop the execution of loops and switch structure. You can stop loops like for, foreach, while and do while. The Switch conditional statement also uses the break statement when the case is met. For loops, you will have to manually check for a condition and depending upon the outcome, you can exit the loops that are nested inside multiple levels.


Break also takes in a numeric argument. This number tells how many levels you want the break statement to end.


Die and Exit vs. Break

Well, they are completely different things. Die and exit are used to stop the execution of an entire script while break is used to exit loops and switch statements which are enclosed with curly braces {}.

You may also like

Comments are closed here.


Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 2 other subscribers