Friday, January 30, 2026
HomeLanguagesHow to terminate execution of a script in PHP ?

How to terminate execution of a script in PHP ?

In this article, we are going to discuss how to terminate the execution of a PHP script.

In PHP, a coder can terminate the execution of a script by specifying a method/function called the exit() method in a script. Even if the exit() function is called, the shutdown functions and object destructors will be executed without interruption. We can pass a message as a parameter to the exit() function which returns the message as an output before terminating the execution of the script.

exit(): The function terminates the execution of a script. It accepts a string that is returned as a message before the termination of code/script. The exit() function can even accept an integer that is in the range of 0-254. The function will not return an integer. The exit() function treats an integer as an exit code. It is a language construct and can be used without parenthesis, if no message/exit code is passed.  

Syntax:

exit(message);

Parameters:

  • The message is a string that is returned before termination of execution.

Let us look into a few example programs on how to terminate the execution of the script.

Example 1: In the below code, we used two exit() function methods with different messages in them. We just specified the exit() functions in the if….else statement. Based on criteria the respective exit() function is called.

PHP




<?php
  
$age = 22;
  
if($age >= 18) {
  
    // Terminating the execution with a message
    exit('Person eligible for Voting');
}
else {
       
    // Terminating the execution with a message
    exit('Person is not eligible for Voting');
}
?>


Output:

Person eligible for Voting

Example 2: The below code shows that any code present below the called exit() function will not get executed and the script will get terminated by returning the message. The second echo statement is not printed in the output because the exit() function is called before the second echo statement’s execution.

PHP




<?php
  
echo "neveropen\n";
exit("The below code will not get executed");
echo "A top Learning Platform";
?>


Output:

neveropen
The below code will not get executed
RELATED ARTICLES

Most Popular

Dominic
32478 POSTS0 COMMENTS
Milvus
122 POSTS0 COMMENTS
Nango Kala
6849 POSTS0 COMMENTS
Nicole Veronica
11978 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12065 POSTS0 COMMENTS
Shaida Kate Naidoo
6987 POSTS0 COMMENTS
Ted Musemwa
7222 POSTS0 COMMENTS
Thapelo Manthata
6934 POSTS0 COMMENTS
Umr Jansen
6917 POSTS0 COMMENTS