How To Stop Your Code From Executing In PHP

How To Stop Your Code From Executing In PHP

·

1 min read

In this tutorial, we will learn how to stop your PHP code from executing further.

As their names may suggest, die() and exit() stops the code from running further.

Usage

We often use die() or exit() when we want to output an error because we've got something wrong. And inside the function, we write the error.

Example

<?php
function not_one($a)
{
if($a==1)
{
die("Code has stopped running because our variable is equal to 1");
}
echo "Great, the input is not one!";
}
not_one(222);
?>

Result

Screen Shot 2021-10-12 at 8.03.23 PM.png

In the above example, we created a function called not_one() that will stop executing if the input of the function is equal to 1 and echo out the text of Code has stopped running because our variable is equal to 1. Otherwise, it will echo text equal to "Great, the input is not one!". Hence, die() or exit() are usually used with if statements. If some criteria is met that makes us want to stop running the code, we use die() or exit() to stop our code from running. Otherwise, we let the remaining code keep running and executing.