What are best practices for handling form validation errors in PHP?

When handling form validation errors in PHP, it is important to provide clear and specific error messages to the user to help them understand what went wrong. One common approach is to store the error messages in an array and display them next to the corresponding form fields. Additionally, you can use CSS to style the error messages to make them more noticeable.

<?php
$errors = [];

// Validate form inputs
if(empty($_POST['username'])){
    $errors['username'] = 'Username is required';
}

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

// Display error messages
if(!empty($errors)){
    foreach($errors as $error){
        echo '<div class="error">' . $error . '</div>';
    }
}
?>