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.
Example:
<?php $filename = "testfile.txt"; $file = fopen($filename, 'r') or die("The file couldn't be found"); echo "File Opened"; ?>
If testfile.txt is present, it opens the file for reading and prints the following output:
File Opened
If testfile.txt is not present, it exits the script and prints the following output:
The file couldn't be found
- 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
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.
Example:
<?php for($i=1;$i<10;$i++) { echo $i; if($i=='4') { break; } } ?>
Output: 1234
Break also takes in a numeric argument. This number tells how many levels you want the break statement to end.
Example:
<?php for($j=1;$j<10;$j++) { for($i=1;$i<10;$i++) { if($j=='5') { break 2; } echo $i; if($i=='4') { echo "<br />"; break; } } } ?>
Output: 1234 1234 1234 1234
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 {}.