PHP Keywords: die/exit

16 February 2019 - 3:28am

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

<?php
echo "a";
exit;

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

die

<?php
echo "a";
die;

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