How can PHP developers ensure that the correct error message is displayed based on the error code provided?

When handling errors in PHP, developers can use the switch statement to check the error code provided and display the corresponding error message. By creating cases for each error code and assigning the appropriate error message to display, developers can ensure that the correct error message is shown based on the error code.

$error_code = 404;

switch ($error_code) {
    case 404:
        $error_message = "Page not found";
        break;
    case 500:
        $error_message = "Internal server error";
        break;
    default:
        $error_message = "An unknown error occurred";
}

echo $error_message;