Reputation: 2685
If I have a form that contains many fields generated dynamically (their names are integer, because they are named after the iteration that generates them). I need to get their values via post or get (this is an issue i will deal with myself, so lets assume its post).
the code for the inputs:
for ($x = 0; $x < 5; $x++)
for ($y = 0; $y < 12; $y++){
echo '<input type="text" name="'.$x.'"> Bar 1<br/>';
}
How can i get all the 12th values in an array on the server side using php? I generally know how to use post, but in this case what should i put inside the brackets of $_POST[]? And what is the correct syntax to make the name an array?
Upvotes: 0
Views: 172
Reputation: 911
Go through the post and ever 12th pull out a value just add a counter. If other posted information is in form, then do a preg match for first part of your key name and then iterate over counter on that name.
foreach ($_POST as $key => $value)
echo "Field ".htmlspecialchars($key)." is ".htmlspecialchars($value)."<br>";
If that approach isn't appealing, JSON encode the values being sent in an array to the php then do a json_decode into a php array and then take out every twelfth element.
Upvotes: 1
Reputation: 5017
Your code will produce twelve input fields with the same name ($x
), which wont work (each input needs a unique name).
If I remember correctly, you can do something like this:
echo '<input type="text" name="'.$x.'[]"> Bar 1<br/>';
and it will generate an array in $_POST: $_POST[$x][0] = 'first', $_POST[$x][1] = 'second', ...
Upvotes: 0