exit, exit(), exit(0), die(), die(0) - How to exit script
These are all identical. I'm pretty sure die()
is just a straight-up alias to exit()
, but even if it isn't, it still acts identically.
When one of these functions is given a string argument, it prints out the string before terminating the process. When it encounters an integer under 255, that integer is considered the return code for the process, which gets passed back to the process which invoked the PHP script. This is particularly useful when writing command line applications (PHP isn't web-only!).
As far as the difference between exit
, exit()
, and exit(0)
, there really is none. There is definitely no difference between the first two because exit
is technically a language construct, not a function, so it can be called with or without parentheses, just like echo
. Returning a code of 0
means "this program ran successfully/without errors", and while I don't know what exactly happens when you don't pass an argument, PHP.net says that an argument-less exit
indicates success, so I would bet it returns 0
, though again PHP.net doesn't show a default for the argument.
As several people have mentioned, die() and exit() are exactly the same.
If you look at the PHP documentation, there are two options for arguments:
An numeric value. This is only useful if you are using PHP from the command line, as opposed to a web server. A value of zero indicates success. Nonzero indicates a failure condition occurred.
A string value. This will be displayed to the browser when the exit occurs.
Instead of die() or exit(), I recommend using exceptions and a custom top-level exception handler to manage failure conditions.
You have more flexibility that way to do things like automatic error logging. Also, if you're using PHP to implement a JSON API, this exception handler can hand back a valid, error-indicating JSON snippet instead.
I would say that in regards with a better semantics die($arg);
should be used for an abnormal or unexpected termination, even when -of course- you still have caught it. And exit($arg);
should be used for a normal (expected / controlled) end of a process, like in break;
for a for
or while
or a switch
structure but with a definitive end.
Nevertheless .. I personally often use a general if { } else { }
structure to control different branches of huge processes or output buffering so not having to use "exit" ..
I also use die($arg)
in simple error-catching semantics like in
$db = mysql_connect([$args]) or die ($error);
...