How can PHP be used to automate the generation of form fields based on a template?

To automate the generation of form fields based on a template in PHP, you can create an array that defines the fields and their properties, then loop through this array to generate the form fields dynamically. This approach allows for easy customization and maintenance of the form fields without having to update each field individually in the HTML code.

<?php
// Define an array of form fields with their properties
$formFields = [
    'name' => ['type' => 'text', 'label' => 'Name'],
    'email' => ['type' => 'email', 'label' => 'Email'],
    'message' => ['type' => 'textarea', 'label' => 'Message']
];

// Loop through the formFields array to generate form fields dynamically
foreach ($formFields as $fieldName => $fieldProps) {
    echo '<label for="' . $fieldName . '">' . $fieldProps['label'] . '</label>';
    if ($fieldProps['type'] === 'textarea') {
        echo '<textarea name="' . $fieldName . '"></textarea>';
    } else {
        echo '<input type="' . $fieldProps['type'] . '" name="' . $fieldName . '">';
    }
    echo '<br>';
}
?>