Tuesday, November 19, 2024
Google search engine
HomeLanguagesDifference between die() and exit() functions in PHP

Difference between die() and exit() functions in PHP

PHP exit() Function: In PHP, the exit() function prints a message and exits the application. It’s often used to print a different message in the event of a mistake. Use exit() when there is not an error and have to stop the execution.

Syntax:

exit("Message goes here");
or
exit();

Example:

exit("This request is processed");

Program 1:

PHP




<?php
   exit ("This is an exit function in php");
   echo "This will not printed because "
    . "we have executed exit function";
?>


Output:

This is an exit function in php

Program 2:

PHP




<?php
  $a = 10;
  $b = 10.0;
  if($a == $b) {
    exit('variables are equal');
  }
  else {
    exit('variables are not equal');
  }
?>


Output:

variables are equal

PHP die() Function: In PHP, die() is the same as exit(). A program’s result will be an empty screen. Use die() when there is an error and have to stop the execution.

Syntax:

die("Message goes here"); 
or 
die();

Example:

die('Oops! Something went wrong');

Program:

PHP




<?php
    $num = 1;
 
    // die can only print string values,
    // hence there will be no output
    die($num);
?>


Output:

No Output

Note: The output for the above program will be an empty screen because it is similar to exit(), die() can print only string values.

Differences between die() and exit() Functions:

die()

exit()

The die() method is used to throw an exception The exit() method is only used to exit the process.
The die() function is used to print the message. The exit() method exits the script or it may be used to print alternate messages.
This method is from die() in Perl. This method is from exit() in C.

RELATED ARTICLES

Most Popular

Recent Comments