How can you retain form input data when displaying an error message in PHP?

When displaying an error message in PHP, you can retain form input data by using the $_POST superglobal array to populate the input fields with the previously submitted data. This ensures that users don't have to re-enter all their information if there was an error in the form submission.

<?php
// Check if form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Validate form data
    if (/* validation fails */) {
        $error = "Error message here";
    } else {
        // Process form data
    }
}

// Display form with error message and retain input data
?>
<form method="post">
    <input type="text" name="username" value="<?php echo isset($_POST['username']) ? $_POST['username'] : ''; ?>">
    <input type="email" name="email" value="<?php echo isset($_POST['email']) ? $_POST['email'] : ''; ?>">
    <?php if (isset($error)) { echo $error; } ?>
    <button type="submit">Submit</button>
</form>