One of my student asked me couple of questions – what is the difference between print and echo (which I have covered already here) and the difference between die and exit functions. Well, there’s no difference between exit and die – that’s what the PHP manual for both die and exit says. Most importantly, die and exit are not functions and they are language constructs.
The exit() in PHP is used to print a message and exit the program. It’s generally used to print an alternate message for an error.
<?php exit ("This is an exit function in php"); echo "I'll not be printed, as the program will terminate for executing exit function"; ?>
The exit and die can only print string values.
<?php $x = 1; exit ($x); ?>
The output of the above program will result in blank page, as the exit cannot print values other than string.
The exit can be used to show a customized message to the user, instead of displaying the actual error message. For eg., when a mysql connection fails, instead of displaying the exact error message, exit can be used to print an alternate message.
<?php $con= mysql_connect("hostname","mysqlusername","") or die('We are aware of the problem and working on it'); ?>
The die() in PHP is equivalent to exit(). Below are the few examples.
<?php die("This is a die function in php"); //The below line will not be printed echo "I'll not be printed as the program will terminate after die function"; ?>
Similar to exit, die can print only string values.
<?php //$x = "Some text"; $x = 1; die($x); ?>
The output for the above program will be an empty screen.
Finally, the difference between exit() and die() is NONE.