How can PHP be used to handle a variable number of input fields in a form?

When dealing with a form that has a variable number of input fields, you can use PHP to dynamically handle these fields by using arrays in the form input names. This allows you to iterate over the array of input values in your PHP script, regardless of how many fields were submitted. By using array syntax in the input names, you can easily process multiple input fields with similar names.

<form method="post">
  <input type="text" name="field[]">
  <input type="text" name="field[]">
  <input type="text" name="field[]">
  <input type="submit" name="submit" value="Submit">
</form>

<?php
if(isset($_POST['submit'])) {
  $fields = $_POST['field'];
  
  foreach($fields as $field) {
    echo $field . "<br>";
  }
}
?>