PHP

PHP exit() Function

The exit() is an inbuilt function in PHP it is used to stop the script execution wherever we want, it works almost the same as PHP die() function.

Syntax

exit(message);

Parameter

The exit() function has only one parameter (message).

we can use this function without a message as well.

Example 1

<?php
echo "hello world <br>";
echo "hello world <br>";
echo "hello world <br>";
exit( "can't print");
echo "hello world";
echo "hello world";
?>

Output

hello world
hello world
hello world
can't print

You can use the exit() function without a message as well, see the example below.

Example 2

<?php
echo "hello world <br>";
echo "hello world <br>";
echo "hello world <br>";
exit( );
echo "hello world";
echo "hello world";
?>

Output

hello world
hello world
hello world

Example 3

<?php

try {
               echo 'Executing try ...', PHP_EOL;

               throw new Exception('there is an error');

               exit(1);
} catch (\Throwable $g) {
               echo $g->getMessage() , PHP_EOL;
} finally {
               echo 'Executing finally';
}
?>

In the above example, we used the exit() function with try and catch.

Output

Execute try ... there is an error Execute finally

Conclusion

In this tutorial, we talk about the PHP exit() Function, with and without parameters.

Suggested Article:

Leave a Comment