In what ways can PHP be used to improve the user experience by providing real-time feedback on form input validation before submission?

When a user fills out a form on a website, it can be frustrating to submit the form only to find out that there are errors in the input fields that need to be corrected. By using PHP to provide real-time feedback on form input validation before submission, users can receive immediate feedback on any errors they may have made, allowing them to correct them before submitting the form.

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = $_POST['name'];
    $email = $_POST['email'];
    
    $errors = array();
    
    if (empty($name)) {
        $errors[] = "Name is required";
    }
    
    if (empty($email)) {
        $errors[] = "Email is required";
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = "Invalid email format";
    }
    
    if (!empty($errors)) {
        foreach ($errors as $error) {
            echo $error . "<br>";
        }
    } else {
        // Form submission logic goes here
    }
}
?>