PHP Function Reference

PHP trigger_error() Function



The PHP trigger_error() function is used to trigger a user defined error condition and generates a user-level error/warning/notice message. It can be used in conjunction with the built-in error handler, or with a user defined error handler function set by the set_error_handler() function.

Syntax

trigger_error(message, error_level)

Parameters

message Required. Specify the error message for this error. It is limited to 1024 bytes in length. Any additional characters beyond 1024 bytes will be truncated.
error_level Optional. Specify the error type for this error. It can take values from E_USER family of constants which are:
  • E_USER_ERROR
  • E_USER_WARNING
  • E_USER_NOTICE (default)
  • E_USER_DEPRECATED

Return Value

Returns false if wrong error_level is specified, true otherwise.

Example: trigger_error() example

The example below shows the usage of trigger_error() function.

<?php
$dividend = 100;
$divisor = 0;

if ($divisor == 0) {
  trigger_error("Cannot divide by zero", E_USER_ERROR);
} else {
  echo ($dividend/$divisor);
}
?>

The output of the above code will be:

PHP Fatal error:  Cannot divide by zero in Main.php on line 6

Example: using inside a function

Consider one more example where this function is implemented inside a function and generates error message whenever error condition is met.

<?php
function divide($dividend, $divisor) {
  if ($divisor == 0) {
    trigger_error("Cannot divide by zero", E_USER_ERROR);
  } else {
    echo ($dividend/$divisor)."\n";
  }
}

divide(100, 25);
divide(100, 10);
divide(100, 0);
divide(100, 20);
?>

The output of the above code will be:

4
10

PHP Fatal error:  Cannot divide by zero in Main.php on line 4

❮ PHP Error Handling Reference