What are the best practices for handling form validation and error messages in PHP when creating a contact form?

When creating a contact form in PHP, it is important to implement form validation to ensure that the user inputs the correct data. To handle form validation and error messages effectively, you can check if the form has been submitted, validate each input field, display error messages if validation fails, and process the form data if validation passes.

<?php
// Check if the form has been submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Validate each input field
    $name = $_POST["name"];
    $email = $_POST["email"];
    $message = $_POST["message"];
    
    $errors = array();
    
    if (empty($name)) {
        $errors[] = "Name is required";
    }
    
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = "Invalid email format";
    }
    
    if (empty($message)) {
        $errors[] = "Message is required";
    }
    
    // Display error messages if validation fails
    if (!empty($errors)) {
        foreach ($errors as $error) {
            echo $error . "<br>";
        }
    } else {
        // Process the form data if validation passes
        // Send email, save to database, etc.
        echo "Form submitted successfully";
    }
}
?>