Is there any differences between PHP die() and exit()?

Posted on Aug 12, 2022

Here you will learn the differences between PHP die() and exit()

Photo from Unsplash

Based on the documentation, the PHP die() function is equal to the exit() function.

There’s no technical difference between the die() and exit() function.

There is only a semantic difference between the die() and exit() function:

  • die() is recommended when you stop PHP script because of an exception
  • exit() is used when your PHP script require something from the user

Here’s an example:

// 👇 Using exit
$name = null;
if (!$name) {
    echo "Please input name";
    exit();
}

// 👇 Using die
$name = null;
if (!$name) {
    die("name variable is empty!");
}

While both exit and die do the same thing, die feels like there’s an error with the program, while exit seems like the program needs something from the user.

And that’s the only difference between die() and exit() function.

The guideline is: use exit() when the user needs to do something. Use die() when some expected data is missing.

Level up your programming skills

I'm sending out an occasional email with the latest programming tutorials. Drop your email in the box below and I'll send new stuff straight into your inbox!

No spam. Unsubscribe anytime.