Skip to main content

Command Palette

Search for a command to run...

How To Stop Your Code From Executing In PHP

Updated
1 min read
How To Stop Your Code From Executing In PHP
E

I'm a full-stack web developer who loves building new projects and learning new things

It might not show from my posts, but I'm also quite funny.

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.

E

Hi Eric, sorry this comment doesn't relate directly to this post, but I can't find any other way to connect with you (sorry if I missed something obvious!)

I'm a product manager for Packt Publishing and I'm reaching out because I'm currently developing some new titles around PHP and wondered if that might be something that would interest you?

Thanks for reading and all the best, Elliot

E
Eric4y ago

Hi Elliot, Please send me the details as javasper[at]outlook.com.

More from this blog

Javasper

50 posts

I'm a full stack software developer who loves to building new projects and solving difficult problems.

It might not be obvious from my posts, but I'm actually quite funny.