What are the best practices for handling form data validation and error messages in PHP to ensure a cleaner and more efficient programming style?

When handling form data validation and error messages in PHP, it is best practice to separate the validation logic from the presentation of error messages. This can be achieved by using conditional statements to check the input data and display appropriate error messages if validation fails. Additionally, it is recommended to sanitize and validate user input to prevent security vulnerabilities.

// Example of handling form data validation and error messages in PHP

// Check if form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Validate form data
    $name = $_POST["name"];
    
    if (empty($name)) {
        $error = "Name is required";
    } else {
        // Process the form data
        // ...
    }
}

// Display the form and error message
?>
<form method="post" action="">
    <input type="text" name="name" value="<?php echo isset($name) ? $name : ''; ?>">
    <span style="color: red;"><?php echo isset($error) ? $error : ''; ?></span>
    <button type="submit">Submit</button>
</form>