0

I have a foreach loop with a form inside for each result like so:

foreach($this->results() as $that) {
<form>
<input type="text" name="name[]">
<input type="text" name="this[]">
</form>
}

and so on. My question is how do I each forms data. I understand you can do something like the following:

$_POST['name'][0]; 
$_POST['name'][1];

etc, but is their a way to get this done without knowng how many forms their will be. I mean like foreach loop the $_POST data and get each form?

Many thanks

1
  • Add hidden element into the form which will track the number of forms. <?php $i=0;?> and inside for loop add <input type="hidden" value="$i++" name="formCount"> Commented Jun 13, 2015 at 17:02

3 Answers 3

1
foreach ($_POST['name'] as $val) { /* do what you want, want you want with my value */ }

$_POST['name'] is just an array. Use count or any array function you want on it then.

Sign up to request clarification or add additional context in comments.

2 Comments

What about when it comes to the next $_POST you would have like foreach($_POST['this'] as $val2) {} but then how do you take the first value from name and first value from this so thats one form?
Using a for loop? for ($i=0; $i<count($_POST['name']);$i++) { $_POST['name'][$i]... $_POST['this'][$i] }
0

You can do it like this:

foreach ($_POST['name'] as $val => $value) {}

assuming these rows are being generated by a while loop, and the variable is named like this

  $val = $row['val'];

And then in your form you'd have something like this:

echo  '<input type="hidden" value="'.$val.'" name ="val[]" /><input type="text" name="name['.$val.'] />";

basically the name variable would be identified by the value itself being generated but also appended on a named variable, and then can be fed into your foreach.

Comments

0
foreach ($_POST['name'] as $key => $value) { 
   echo 'key: '.$key.' Value : '.$value;
}

--------------------------

output key: 0 Value : nameValue1 
key: 1 Value : nameValue2

$_POST['name'] is an array, if you get multiple value with key, just get with foreach value

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.