How can PHP arrays be used to repopulate form fields with user input data?

When a form is submitted with user input data, PHP arrays can be used to store this data and then repopulate the form fields with the user's input if there are any validation errors. This can be achieved by storing the user input data in an associative array where the keys correspond to the form field names. When the form is redisplayed, the input fields can be populated with the data from the array using the value attribute.

<?php
// Initialize an associative array to store user input data
$userInput = [];

// Check if the form has been submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Store user input data in the array
    $userInput['name'] = $_POST['name'];
    $userInput['email'] = $_POST['email'];
    // Add more fields as needed

    // Display any validation errors
    // Repopulate form fields with user input data
}
?>

<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
    <input type="text" name="name" value="<?php echo isset($userInput['name']) ? $userInput['name'] : ''; ?>" placeholder="Name">
    <input type="email" name="email" value="<?php echo isset($userInput['email']) ? $userInput['email'] : ''; ?>" placeholder="Email">
    <!-- Add more form fields as needed -->
    <button type="submit">Submit</button>
</form>