All in the <head> – Ponderings and code by Drew McLellan –

PHP Duplicate Names

Quite often when working with HTML forms, it’s necessary to have multiple fields that share the same name attribute. A good example is check boxes and radio buttons, which are grouped based on their name. When the form is submitted, the data is shipped off to a server-side processor whose responsibility it is to interpret the input.

When working with ASP, any values sharing the same name get compiled together as a comma-delimited list. This isn’t an ideal way to work as it can be difficult to split that list back down and be certain that there weren’t stray commas in the input to throw everything off. PHP has a really neat trick whereby if an HTML field name ends in [] it will automatically turn the results into an array. This means you can cycle through the results with absolute certainty that you have collected the data accurately. It also saves you a couple of lines of code, as the most common destination for this sort of data is an array.

The problem arises in that the square brackets PHP uses are not valid characters for use in field names. Whilst a quick test suggests they behave fine in the up-to-date versions of IE and Moz I have running on my desktop, as the characters are out-of-spec they must be consider unsafe, if not harmful, for use. Unfortunately, this leaves me in a sticky situation – how do I deal with multiple fields using the same name? There must be a solution, but I can’t seem to find it.