What is the difference between echo('exit'); die; and die('exit');?

Naftali aka Neal picture Naftali aka Neal · Apr 28, 2011 · Viewed 10.9k times · Source

I have seen some code do this:

if(something){
    echo 'exit from program';
    die;
}
...more code

And others that just use die:

if(something)   die('exit from program');
...more code

Is there any inherent difference in when it would end the program, should I be aware of the code that comes after it? etcetera

UPDATE

I am asking mainly, if it is a coding style, or if there is a real reason why some is coded one way versus another. I am not asking what the difference between exit and die is.

Answer

meagar picture meagar · Apr 28, 2011

No, there is no difference; they will both write "exit" to STDOUT and terminate the program.

I would prefer the die("exit") method as it's less typing, easier to comment out and semantically clearer.

As far as "speed", why would you care which is faster? Do you need your program to die really quickly?

RE: Your update

... any inherent difference in when it would end the program ...

There is no difference, inherent or otherwise. They're identical. The second option, die('exit'), is a single statement, and so requires no braces when used with an if statement; this has nothing to do with the die and everything to do with blocks and flow control in C-style languages.

RE: Your comment/second update

Which way you die is a matter of personal preference. As I said, they are identical. I would choose the 2nd option for the reasons listed above: Shorter, clearer, cleaner, which amounts to "better" in my opinion.

The difference between exit and die is that exit allows you to return a non-zero status, while die returns 0. Neither function is "better", they serve different purposes.