How can multiple form fields be dynamically generated in PHP based on user input?

To dynamically generate multiple form fields in PHP based on user input, you can use a loop to iterate through the number of fields the user wants to generate. You can then output the form fields within the loop, incrementing a counter to give each field a unique name.

<?php
if(isset($_POST['num_fields'])) {
    $numFields = $_POST['num_fields'];
    
    for($i = 1; $i <= $numFields; $i++) {
        echo '<input type="text" name="field_' . $i . '" placeholder="Field ' . $i . '"><br>';
    }
}
?>

<form method="post">
    <label for="num_fields">Number of Fields:</label>
    <input type="number" name="num_fields" id="num_fields">
    <input type="submit" value="Generate Fields">
</form>