Open In App

How to terminate execution of a script in PHP ?

Improve
Improve
Like Article
Like
Save
Share
Report

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 "GeeksforGeeks\n";
exit("The below code will not get executed");
echo "A top Learning Platform";
?>


Output:

GeeksforGeeks
The below code will not get executed


Last Updated : 11 Jun, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads