Skip to content
Related Articles

Related Articles

PHP trigger_error() Function

View Discussion
Improve Article
Save Article
  • Last Updated : 08 Sep, 2021

The trigger_error() function is an inbuilt function in PHP that has the capacity to act as a built-in error handler. This function is generally used by programmers to trigger or generate user level errors, notices or messages. It returns a Boolean value i.e. it returns TRUE on success and FALSE on failure of the expression.

Syntax:

bool trigger_error(string $message, int $error_level);

Here, $message parameter is the message that is to be displayed and it is of string type whereas $error_level is used to describe the type of error that has to displayed and it is of integer type. For any trigger_error() function, $message is required and $error_level can be optional depending upon the user requirement and the maximum length for $message is 1024 bytes.

Example 1: In this example, a user defined function doFunction($var) accepts one value as a parameter inside that function the parameter will be checked if the value will be numeric then $var.”is numeric” will be printed otherwise an error will be thrown with the message “variable must be numeric” and this is done though trigger_error() function.

PHP




<?php
  
function doFunction($var) {
    if(is_numeric($var)) {
        echo $var.' is numeric';
    
      else {
        trigger_error('variable must be numeric');
    }
}
  
$new_var = 'GFG';
doFunction($new_var);
  
?>


Output:

PHP Notice:  variable must be numeric in 
/home/d87c8897dcede28086b7e4f06f5fafc7.php on line 9\

Example 2: By default using a trigger_error() function will generate a PHP Notice however user can also generate PHP errors or PHP warnings by adding parameters within the trigger_error() function as demonstrated in the below example. 

In this example, we have created a divide function that takes two parameters if the value of $second will be equal to zero, the trigger_error() function will throw a PHP fatal error since in the parameter E_USER_ERROR  is passed along with error message to trigger_error() and if the value for $second will not be equal to zero then $first will be divided by $second and the result will be displayed.

PHP




<?php
    
function divide($first,$second) {
    
    if ($second == 0) {
        trigger_error("Cannot divide by zero", E_USER_ERROR);
      }
      else {
        echo $first/$second ;    
      }
}
  
divide(2,0)
  
?>


Output:

PHP Fatal error:  Cannot divide by zero in 
/home/5152fc6f9b996848e7b1f855e7d0b5b9.php on line 6

Reference: https://www.php.net/manual/en/function.trigger-error.php


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!