Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

php - What is the expected order of an array submitted in an HTML form?

I'm wondering if there is any sort of guarantee on the order of POST variables I will see on the server side.

My use case is I have a form that a user will fill out to enter a list of names and emails. I'm using a table rows, each of which has two inputs:

<table>
<tr>
<td><input type='text' name='name[]' /></td>
<td><input type='text' name='email[]' /></td>
</tr>
<tr>
<td><input type='text' name='name[]' /></td>
<td><input type='text' name='email[]' /></td>
</tr>
</table>

The row might be cloned via javascript to allow the user to type in more names and emails so I won't know ahead of time how many will be submitted.

On the server side, I see $_POST['email'] and $_POST['name'] set but I am wondering if I can safely assume $_POST['email'][0] will correspond to $_POST['name'][0], $_POST['email'][1] will correspond to $_POST['name'][1], and so on. Some basic testing seem to indicate yes but I'm wondering if there is a guarantee or if I'm just getting lucky.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

why not add a grouping key like:

<td><input type='text' name='user[0][name]' /></td>
<td><input type='text' name='user[0][email]' /></td>
</tr>
<tr>
<td><input type='text' name='user[1][name]' /></td>
<td><input type='text' name='user[1][email]' /></td>

and then manuall set the user indexes when you clone based on the current number. This way everything is already coallated.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...