What best practices should be followed when writing PHP code to validate form input, in order to ensure accurate error messages and user-friendly experiences?

When validating form input in PHP, it is important to follow best practices to ensure accurate error messages and a user-friendly experience. One way to achieve this is by using conditional statements to check each input field for errors and displaying specific error messages for each validation rule that is not met. Additionally, it is recommended to sanitize and validate user input to prevent security vulnerabilities.

// Example of validating form input in PHP

$name = $_POST['name'];
$email = $_POST['email'];

$errors = [];

// Validate name field
if(empty($name)) {
    $errors['name'] = 'Name is required.';
}

// Validate email field
if(empty($email)) {
    $errors['email'] = 'Email is required.';
} elseif(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $errors['email'] = 'Invalid email format.';
}

// Display error messages
if(!empty($errors)) {
    foreach($errors as $error) {
        echo $error . '<br>';
    }
}