In PHP, error_get_last() returns information about the most recent error that happened in your script, or null if there has not been one.
It is useful when an error was hidden with the @ operator, or when you want to inspect what went wrong inside a shutdown function. The result is an array with the keys type, message, file and line, so you can see what happened and where.
Syntax
Call error_get_last() with the values you need. Start with this line.
PHP
$error = error_get_last();
Call
What it does
error_get_last()
Returns an array describing the last error, or null if there was none.
error_get_last()['message']
Reads just the error text. Check for null first.
error_get_last()['type']
Reads the error level number, such as 2 for E_WARNING.
Only the very last error is kept, so a newer error replaces an older one. Use error_clear_last() to reset it. Even errors hidden with @ are recorded.
Library declarations
PHP
error_get_last(): ?array
Parameters
Parameter
Description
—
This function takes no parameters.
Return Value
Return Value
Description
array
An associative array with the keys type (int), message (string), file (string) and line (int) describing the most recent error.
null
Returned when no error has happened yet, or when error_clear_last() was called.
PHP Examples
Example 1 — Reading a Hidden Error
The @ operator hides an error from the screen, but error_get_last() can still tell you about it.
Could not read the file.
Message: file_get_contents(missing-file.txt): Failed to open stream: No such file or directory
Is warning: yes
How It Works
file_get_contents() cannot find the file, so it returns false and raises a warning.
The @ operator hides the warning, but PHP still records it.
We only call error_get_last() after confirming that the read failed.
The message explains the reason, and the type matches E_WARNING.
Frequently Asked Questions
It returns an array with the keys type, message, file and line for the most recent error. If no error has happened, it returns null.
Yes. The @ operator only hides the error message. PHP still records the error, so error_get_last() can read it afterwards.
Register a function with register_shutdown_function(), and call error_get_last() inside it. If the result is not null and the type is a fatal one such as E_ERROR, the script stopped because of that error.
Either no error has happened yet, or error_clear_last() was called after the last one. A custom error handler that returns true also stops PHP from recording the error.
Call error_clear_last(). After that, error_get_last() returns null until a new error occurs.