Reputation: 717
i have a series of questions pulled from a database and need to loop radio buttons for each question. I need all of the answers returned to an array that looks something like this
$answer_grp1 = array("T", "T", "T");
My code looks like this. What is the correct (name=??) syntax to get an array into $_POST['answer_grp1']
<?php foreach ($questions as $question):
if ($question['q_type']==1): ?>
<tr>
<td style="width:5%;"><?= $question['q_number'] ?></td>
<td style="width:15%;">
T<input type="radio" name=answer_grp1[] value="T" />
F<input type="radio" name=answer_grp1[] value="F" />
</td>
<td><?= $question['q_text'] ?></td>
</tr>
<?php endif;
endforeach; ?>
Upvotes: 0
Views: 18207
Reputation: 1842
I would be inclined to use a for loop instead:
<?php
for ($i = 0; $i < count($questions); $i++) {
$question = $questions[$i];
if ($question['q_type']==1): ?>
<tr>
<td style="width:5%;"><?= $question['q_number']; ?></td>
<td style="width:15%;">
T<input type="radio" name=answer_grp1[<?php print $i; ?>] value="T" />
F<input type="radio" name=answer_grp1[<?php print $i; ?>] value="F" />
</td>
<td><?= $question['q_text']; ?></td>
</tr>
<?php endif;
endfor; ?>
This is with your code:
<?php
$i = 0;
foreach ($questions as $question):
if ($question['q_type']==1): ?>
<tr>
<td style="width:5%;"><?= $question['q_number']; ?></td>
<td style="width:15%;">
T<input type="radio" name=answer_grp1[<?php print $i; ?>] value="T" />
F<input type="radio" name=answer_grp1[<?php print $i; ?>] value="F" />
</td>
<td><?= $question['q_text']; ?></td>
</tr>
<?php endif; ?>
<?php
$i++
endforeach; ?>
Upvotes: 3
Reputation: 472
You would use
$_POST['answer_grp1'][0]
$_POST['answer_grp1'][1]
... and so on.
If all the answers were going to be in this one array, you could also loop through it like this:
for ($x=0; $x<count($_POST['answer_grp1']); $x++)
{
$value = $_POST['answer_grp1'][$x];
}
As long as all the fields fall within one <form>
tag and you submit the form, then the array should be available in the $_POST
global.
Your naming for each input, answer_grp1[]
is correct; however you should add quotes around the name.
You should also be adding semi-colons after your question output - change this:
<?= $question['q_text'] ?>
To this:
<?= $question['q_text']; ?>
Upvotes: 0