Skip to content

HTML/PHP - Form - Input as array

To create an HTML form that submits an array as a form parameter, you can use the name attribute of the input element and give it a value in the form of an array.

For example:

Example of creating an HTML form that submits an array as a form parameter

php
<form method="POST">
  <input type="text" name="colors[]" value="red">
  <input type="text" name="colors[]" value="green">
  <input type="text" name="colors[]" value="blue">
  <input type="submit" value="Submit">
</form>

This will create an HTML form that submits an array called colors when the form is submitted. The values of the colors array will be the values of the input elements in the form.

In PHP, you can access the colors array like this:

Example of accessing the submitted form array parameter in PHP

php
$colors = $_POST['colors'];

This will assign the colors array to the $colors variable. You can then loop through the array and access the individual values like this:

Example of looping through an array and access the individual values in a HTML and PHP form

php
<?php

foreach ($colors as $color) {
  echo $color;
}

This will output the values of the colors array (i.e., "red", "green", and "blue") one at a time.

Dual-run preview — compare with live Symfony routes.