1. Home
  2. Programming Tools
  3. What’s the difference between die and exit functions in PHP?

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

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.

exit():

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.

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

E.g:

<?php
 $con= mysql_connect("hostname","mysqlusername","") or die('We are aware of the problem and working on it');
?>

die() function:

The die()  in PHP is equivalent to exit(). Below are the 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, 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.

Finally, the difference between exit() and die() is NONE.

Updated on September 1, 2017

Was this article helpful?

Related Articles

Leave a Comment