How can PHP errors be stored in a variable instead of being directly output?

To store PHP errors in a variable instead of being directly output, you can use the `set_error_handler()` function to define a custom error handler that captures the errors and stores them in a variable. This allows you to handle errors in a more controlled manner, such as logging them to a file or displaying them in a specific format.

// Custom error handler function
function customErrorHandler($errno, $errstr, $errfile, $errline) {
    $error = "Error: [$errno] $errstr in $errfile on line $errline";
    // Store the error in a variable
    $errors[] = $error;
}

// Set custom error handler
set_error_handler("customErrorHandler");

// Trigger a PHP error
echo $undefinedVariable;

// Retrieve stored errors
if(isset($errors)) {
    foreach($errors as $error) {
        echo $error . "<br>";
    }
}