Skip to content
PHP Logo

What are the advantages of using an array in the name attribute of form fields in PHP?

Using an array in the name attribute of form fields in PHP allows for easier handling of multiple form inputs with similar names. This is especially useful when dealing with dynamic form elements or when submitting multiple values for the same input name. By using an array, you can easily loop through the form data and access each input value without having to manually differentiate between them.

php
<form method="post">
  <input type="text" name="user[name]">
  <input type="email" name="user[email]">
  <input type="text" name="user[phone]">
  <input type="submit" value="Submit">
</form>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
  $userData = $_POST['user'];
  
  foreach ($userData as $key => $value) {
    echo $key . ": " . $value . "<br>";
  }
}
?>