'Accessing POST Data by Index

Is there any way to access POST data by index, rather than accessing it through keys? I'd like the following code to work:

for($x = 0; $x < count($_POST); $x++)
    echo $x . ": " . $_POST[$x];

(Yes, I know that count in the loop is bad, just using it for simplicity)

The problem is that apparently I can't access the $_POST variable by index, it has to be accessed by key. The reason I can't use keys is because I'm going to have variable form data, so there could be more or less in the POST, so I need to be able to loop through a variable number of keys, with variable names.

Any help is appreciated!

EDIT: To clarify, I was confused because I had previously assumed that PHP arrays behaved almost like C++ enumerations.



Solution 1:[1]

Use foreach() instead, it also works on numeric arrays.

foreach ($_POST as $key=>$val)
    printf("%s: %s\n", $key, $val);

Solution 2:[2]

Is there any way to access POST data by index, rather than accessing it through keys?

No, it doesn't have numerical indexes.

The reason I can't use keys is because I'm going to have variable form data, so there could be more or less in the POST, so I need to be able to loop through a variable number of keys, with variable names.

You can loop through associative arrays. See the documentation of foreach.

foreach (array_expression as $key => $value)
  statement

Solution 3:[3]

Why not just use foreach

foreach ($_POST as $key => $value) {
}

?

Solution 4:[4]

foreach($_POST as $key=>$value) {
    echo $key. ":" .$value;
}

Solution 5:[5]

Indexes and keys are the same thing. The key is either a number (e.g. $_POST[0]) or it's a string (e.g. $_POST['foo']). It cannot be both. You cannot access $_POST['foo'] through $_POST[0].

Solution 6:[6]

Technically possible, though foreach is superior:

$postVals = array_value($_POST);
$postCount = count($_POST);
for($x = 0; $x < $postCount; $x++)
    echo $x . ": " . $postVals[$x];

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Quentin
Solution 3 fvu
Solution 4 Joshua Lückers
Solution 5 deceze
Solution 6 meiamsome