Will data order in post form be the same to it in

2019-02-22 06:04发布

问题:

Assuming there are 5 inputs in web form

<input name='the_same[]' value='different' />
<input name='the_same[]' value='different' />
<input name='the_same[]' value='different' />
<input name='the_same[]' value='different' />
<input name='the_same[]' value='different' />

When server side receive the post data, i use a foreach to accept data, say

$the_same = new array();
foreach($_POST['the_same'] as $data)
    $the_same[] = $data;

Will the order of data saved in server side be the same to it in web form? and cross browsers, it could be a criteria all browsers follow.

回答1:

Well, the W3C recommentation on HTML forms does say:

The control names/values are listed in the order they appear in the document.

Still, I'd consider it a bit risky to have your app depend critically on that detail.



回答2:

PHP already handles converting POSTed/GETed variables into arrays when you put [] after the name. Do that instead of getting it wrong yourself.



回答3:

Better way to do in html:

<input name='the_same[]' value='different' />

Then in server:

$the_same = new array();
foreach($_POST['the_same'] as $data) // or $_GET if you prefer
    $the_same[] = $data;

In this way no variable will be overwrite.



回答4:

if you want to have it in an order, you may use the dynamic variables or simply access the array explicitly

the_same1 the_same2 the_same3

since you know the names anyway, you can access them easily

$the_same = array();
for($i=1; ; $i++){
    $tmp =$_REQUEST["the_same".$i]
    if( empty($tmp) ){
            // no more stuff
            break;
    }
    $the_same[] = $tmp;
}


回答5:

If you change the name of your input to the_same[] - $_REQUEST['the_same'] will become an array of those values, first to last in element order (all current browsers I believe).

You can also specify a specific order if you need, or even use string keys. For instance, an <input name='the_same[apple][2]'/> would become $_REQUEST['the_same']['apple'][2]

Without using the [] on the input names, PHP will only see the last value. The other values will be 'overwritten' by the later value when the $_REQUEST/$_GET/$_POST arrays are constructed.

An example of using that to your advantage could be with a checkbox, as the HTML checkbox only submits a value when checked, you may want to submit a "not checked" value somtime:

<input type='hidden' name='check' value='not checked' />
<input type='checkbox' name='check' value='checked' />


回答6:

Most likely yes, but you should not assume this. It depends on your browser how the inputs are being send, and aditionally PHP does not guarantee that a foreach loop iterates in the same order as the elements were added.

It is a bad practise to give your inputs the same name.

You could append an index after each name value (even with javascript if you want), and then read this in PHP to be sure the order is maintained.



标签: php http post