Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the order of INPUTS in a POST guaranteed for array inputs in PHP?

I have a form where users enter an unbounded number of rows of data. They arrive at the form by entering whatever number of rows on the screen that they desire.

<?php
$numRows = $_GET['NUM_ROWS_REQUESTED'];

?>
<form method="post">
<?php
for($i = 0; $i < $numRows ;$i++) {
  $uuid = uniqid();
?>

  <input type="text" name="MYDATA[<?php print $uuid; ?>][FIRST_NAME]" />
  <input type="text" name="MYDATA[<?php print $uuid; ?>][LAST_NAME]" />
<?php
}
?>
</form>

I'm wondering if, when the form is posted and I receive these records in the $_POST['MYDATA'] array if I can be guaranteed that they will be ordered in the same sequence as they were posted on the screen. Or will they be ordered by the uniqid() that's randomly generated?

The reason I use a unique ID instead of just integers which would be easier to sequence, is that users can remove rows and add additional rows using javascript on that page. It would be too difficult to check for collisions.

like image 551
aw crud Avatar asked Dec 09 '10 16:12

aw crud


People also ask

What is the use of $_ POST array in PHP?

PHP $_POST is a PHP super global variable which is used to collect form data after submitting an HTML form with method="post".

What is $_ POST array?

$_POST is a predefined variable which is an associative array of key-value pairs passed to a URL by HTTP POST method that uses URLEncoded or multipart/form-data content-type in request. $HTTP_POST_VARS also contains the same information, but is not a superglobal, and now been deprecated.

What is Post array php?

Use the POST Method to Send an Array From a Form in PHP. We use the POST method to send data from a form in PHP. The POST method is an HTTP request method that creates or adds resources to the server. We use it when we have to send sensitive information like passwords.


2 Answers

The W3 spec doesn't include rules on what order a form's values should be assembled into a data set, so technically you cannot be sure. On the other hand, I've not seen a case (from numerous browsers on numerous OSes over the years) where data hasn't been supplied in source-listing-order. I've not really tested for cases when changing the default (UI generated) tabindex values.

You could always sort the array (asort) after you've received it to be sure about what order you're reading values.

like image 151
Rudu Avatar answered Sep 25 '22 23:09

Rudu


It's sort of guaranteed by HTML4.01 (for -urlencoded, but it's assumed to be identical for /form-data), and all current browsers submit the form fields in the order they are listed in the document.

So yes, they are ordered by their appearance, not by the random uuid.

like image 37
mario Avatar answered Sep 22 '22 23:09

mario