0

I need to create multiple forms with a single submit (save) button.

<?php for ($i = 0; $i < count($c); $i++): ?>

    <div>            
        <input type="radio" name="gender[<?php echo $i ?>]" id="gender_<?php echo $i ?>_male" value="male" />
        <label for="gender_<?php echo $i ?>_male">Male</label>
        <input type="radio" name="gender[<?php echo $i ?>]" id="gender_<?php echo $i ?>_female" value="female" />
        <label for="gender_<?php echo $i ?>_female">Female</label>
    </div>

    <div>
        <div><label for="Name_<?php echo $i ?>">Name:</label></div>
        <div><input type="text" name="Name[]" id="Name_<?php echo $i ?>" /></div>
    </div>    

<?php endfor ?>

I had to name the radio buttons as gender[0] ... gender[1] so that the groups have unique names. But I've named Name as Name[].

My question is, do I name Name[] as Name[0] ... Name[1] instead so that the flow is constant ? I mean, can $_POST['Name'][0] ever be mapped to gender[1] ?

Community
  • 1
  • 1
anjanesh
  • 3,771
  • 7
  • 44
  • 58
  • _"can $_POST['Name'][0] ever be mapped to gender[1] ?"_ .... what? No, that would defeat the entire purpose of naming ANYTHING if it could be assigned differently by "random" - Other than that, see Marc B's answer. – Epodax Mar 14 '16 at 17:24

2 Answers2

2

Browsers will always submit fields in the same order. This is required by the HTML specification:

Loop: For each element field in controls, in tree order, run the following substeps:

So, unless you start disabling fields, you won't have a problem.

Being explicit might make it a little easier to read your code though.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

Browsers TEND to submit fields in the same order they're listed in the html, but as far as I know, there's no REQUIREMENT this be the case. So, if you had

<input name="foo[]" ...>    ... should become $_POST['foo'][0]
<input name="foo[]" ...>    ... should become $_POST['foo'][1]
<input name="foo[]" ...>    ... should become $_POST['foo'][2]

But since there's no requirement, you may well get the fields in some OTHER order. If you're using the [] naming hack, and doing multiple fields that must be associated with each other, you may be better off explicitly listing indexes, to ensure that the field association is maintained, e.g.

<input name="firstname[0]"> <input name="lastname[0]">
<input name="firstname[1]"> <input name="lastname[1]">
etc...

Without this, your user name could enter John Doe and Jane Smith, but receive John Smith and Jane Doe at the server. Not very likely, but... better safe than sorry.

Marc B
  • 356,200
  • 43
  • 426
  • 500