What’s the difference between die and exit functions in PHP?

Updated on March 9, 2022

One of my students asked me a 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 a slight difference between die() and exit(). Most importantly, die and exit are not functions and they are language constructs.

exit():

The exit() in PHP is used to print a message and exit the program. It’s generally used to print an alternate message or exit the program. Use exit() when there is no error and you need to stop the execution of the program.

difference between exit and die

E.g:

<?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.

E.g:

<?php
$x = 1;
exit ($x);
?>

The output of the above program will result in a blank page, as the exit cannot print values other than string.

The die()  in PHP is equivalent to exit() but as said with a slight difference. Use die() when there’s an error and have to stop the execution.

Below are a few examples.

E.g:

<?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(), the die() can print only string values.

E.g:

<?php
//$x = "Some text";
$x = 1;
die($x);
?>

The output for the above program will be an empty screen.

The die() 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,  <em>die()</em> can be used to print an alternate message.

E.g:
<pre>&lt;?php
$con= mysql_connect(“hostname”,”mysqlusername”,””) or die(‘We are aware of the problem and working on it’);
?&gt;</pre>
<strong>die() function:</strong>

Finally, the difference between exit() and die() is: exit() is used to stop the execution of the program, and die() is used to throw an exception and stop the execution.

Was this article helpful?

Related Articles

Leave a Comment