What are some common methods in PHP to validate form inputs and display error messages if inputs are incomplete?

When working with forms in PHP, it is important to validate user inputs to ensure data integrity and prevent potential security vulnerabilities. One common method to validate form inputs is to use conditional statements to check if required fields are empty and display error messages if they are. This can be achieved by checking if the form has been submitted, validating each input field, and storing error messages in an array to be displayed to the user.

<?php
$errors = [];

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Validate form inputs
    if (empty($_POST["name"])) {
        $errors[] = "Name is required";
    }

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

    // Display error messages
    if (!empty($errors)) {
        foreach ($errors as $error) {
            echo $error . "<br>";
        }
    } else {
        // Process form data if no errors
        // Insert code to handle form submission here
    }
}
?>