PHP user_error() Function
The PHP user_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.
This function is an alias of trigger_error() function.
Syntax
user_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:
|
Return Value
Returns false if wrong error_level is specified, true otherwise.
Example: user_error() example
The example below shows the usage of user_error() function.
<?php $dividend = 100; $divisor = 0; if ($divisor == 0) { user_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) { user_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