Are there any best practices for organizing PHP code to ensure error messages are displayed correctly in HTML?

When displaying error messages in HTML using PHP, it is important to properly organize your code to ensure that error messages are displayed correctly. One best practice is to separate your PHP logic from your HTML markup by using PHP to set variables for error messages and then displaying them within the HTML structure. This helps to keep your code clean and maintainable.

<?php
// Initialize error message variable
$error_message = "";

// Check for errors and set error message
if ($error_condition) {
    $error_message = "An error occurred!";
}

?>

<!DOCTYPE html>
<html>
<head>
    <title>Error Handling</title>
</head>
<body>

<?php
// Display error message if it exists
if (!empty($error_message)) {
    echo "<p>Error: $error_message</p>";
}
?>

</body>
</html>