The San Antonio Web Development Group Message Board › Arrays in forms

Arrays in forms

A former member
Post #: 21
PHP allows you to use arrays in HTML forms. This is accomplished by giving the same "name" to the elements you wish to have in an array suffixed with brackets. Here's an example:

<form method="post">
  <input name="vehicles[]" type="text" value="truck">
  <input name="vehicles[]" type="text" value="car">
  <input name="vehicles[]" type="text" value="suv">
  <input name="vehicles[]" type="text" value="bus">
  <input type="submit">

If you sent that form to a PHP script, you could use the following code in your script:


And get the following output:

     [vehicles] => Array
            [0] => truck
            [1] => car
            [2] => suv
            [3] => bus


That's neat and cool, but I'm wondering if that HTML is legal. I know it's valid to use the same "name" attribute for radio buttons and checkboxes, but what about text fields? I can't find anything in the specs about it:­

I'm also wondering if Javascript doesn't play well with brackets used in "name" attributes.
user 4498413
San Antonio, TX
Post #: 1

I've looked around and I can't find anything on the subject. What I would try doing is create a simple page with a doctype switcher and run it through a validator to see which doctypes throw an error with that type of notation.
A former member
Post #: 1
Using brackets in a form input name is not something you want to do. It does not validate under w3c standards.
A former member
Post #: 22
There are some good discussions on this over at on the PHP and HTML FAQ page.

Officially, it looks like the brackets are legal inside input names (in either HTML or XHTML). Practically, I would avoid them and look for another approach if the need arises.
Jason S.
Group Organizer
San Antonio, TX
Post #: 2
I use them for multiple checkboxes all the time, and have never had a problem.

You can even make them multidimensional. That can get fun.
Powered by mvnForum

Our Sponsors

Sign up

Meetup members, Log in

By clicking "Sign up" or "Sign up using Facebook", you confirm that you accept our Terms of Service & Privacy Policy