How can PHP be used to display custom error messages for specific form fields?

To display custom error messages for specific form fields in PHP, you can validate the form data and store any errors in an associative array with the field names as keys. Then, you can check if there are any errors for a specific field and display the corresponding error message.

// Validate form data
$errors = [];

if(empty($_POST['username'])){
    $errors['username'] = "Username is required.";
}

if(empty($_POST['email'])){
    $errors['email'] = "Email is required.";
}

// Display error messages for specific fields
if(isset($errors['username'])){
    echo $errors['username'];
}

if(isset($errors['email'])){
    echo $errors['email'];
}