Welcome to my series on every PHP keyword and its usage. Today’s item: die/exit.

These two items are equivalent, so I’ll describe both of them here. When you use die or exit, the script immediately exits.

It can take an optional parameter of either a string, which will be displayed to the user, or an integer exit code between 0 and 254, which is only relevant if you’re writing a command line script.

Personally, I prefer to use die when I’m trying to debug some tricky code, and exit when I want the code to come to a halt.

Usage

exit

1
2
3
4
5
6
<?php
echo "a";
exit;

// This statement will not be run
echo "b";
1
2
3
<?php
// This message will be echoed to the user
exit("An error has occurred");
1
2
3
<?php
// This exit code will not be outputted
exit(1);

die

1
2
3
4
5
6
<?php
echo "a";
die;

// This statement will not be run
echo "b";
1
2
3
<?php
// This message will be echoed to the user
die("An error has occurred");
1
2
3
<?php
// This exit code will not be outputted
die(1);