Are there recommended best practices for structuring PHP code to handle form validation errors more efficiently?

When handling form validation errors in PHP, it is recommended to separate the validation logic from the presentation logic to improve code readability and maintainability. One approach is to use an associative array to store the validation errors and display them to the user after form submission. This way, the code becomes more organized and easier to manage.

<?php
$errors = [];

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Validate form fields
    if (empty($_POST["username"])) {
        $errors["username"] = "Username is required";
    }

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

    // Check for any validation errors
    if (empty($errors)) {
        // Process form data
    }
}

?>

<form method="post" action="">
    <input type="text" name="username" placeholder="Username">
    <?php if(isset($errors["username"])) { echo $errors["username"]; } ?>
    <br>
    <input type="email" name="email" placeholder="Email">
    <?php if(isset($errors["email"])) { echo $errors["email"]; } ?>
    <br>
    <button type="submit">Submit</button>
</form>