PHP exit Function | Print a Message and Exit Script

PHP exit is a very useful and important inbuilt function in PHP. It prints a message and exits the current running script. Therefore, any code after the exit function will not be executed. Also, shutdown functions and object destructors are always executed even after the exit function. In this article, we will discuss the PHP exit Function. Also, we will discuss a few examples of using it.

Note: This function is an alias of PHP die Function.

Syntax

exit ( $status = 0 );

Parameters

The PHP exit function expects only one optional parameter, $status.

  • If $status is a string, the function prints the string before exiting.
  • If $status is an integer, the function will use that value as the exit status code without printing it. Exit Statuses should be in the range of 0 to 254. However, PHP reserves 255 for its use and it should not be used. Also, status 0 terminates the program successfully.

Return Value

The PHP exit Function does not return any value.

Examples

Let’s consider a few examples of using the exit function in PHP.

Example 1: Basic Operation

<?php 
  
	echo 'This is a basic test program';

	echo 'We will check exit function';

	exit ('Die Executed');

	echo 'This line will not be executed';
  
?> 

In the above example, the script will execute only lines 1, 2 and 3. After encountering the exit function, the script will terminate and it will not execute any code after that.

OUTPUT:
This is a basic test program
We will check exit function
Die Executed

Example 2: Exit with Integer Status

Similarly, if you pass an integer value to the function, the function will exit with that status code without printing that value.

<?php 
  
	echo 'This is a test program';

	echo 'We will check die function';

	exit (0);

	echo 'This line will not be executed';
  
?> 
OUTPUT:
This is a test program
We will check die function

Example 3: Other ways to call

Likewise, you can also call the function without any brackets or passing any parameters.

<?php

    exit;  //Correct Way of calling
    exit(); //This is also correct

?>

The exit is an alias of PHP die Function. All the functionalities present in die work exactly the same in exit.

Conclusion

In this example, we discussed the PHP die Function. It is very useful in debugging and terminating the script in between. You can read more about it on the Official PHP Documentation. Additionally, you can read about more articles on PHP on Concatly.

Spread the Knowledge
Categories:

Leave a Reply

Your email address will not be published. Required fields are marked *