I would like to write PHP code that loops through rows of a table and posts both text input and a radio selection from each row.
Example HTML
<body>
<form method="post" action="table.php">
<table>
<tr>
<td><input type="text" name="name[]"></td>
<td><input type="radio" name="radio1" value="+">+</td>
<td><input type="radio" name="radio1" value="-">-</td>
</tr>
<tr>
<td><input type="text" name="name[]"></td>
<td><input type="radio" name="radio2" value="+">+</td>
<td><input type="radio" name="radio2" value="-">-</td>
</tr>
<tr>
<td><input type="text" name="name[]"></td>
<td><input type="radio" name="radio3" value="+">+</td>
<td><input type="radio" name="radio3" value="-">-</td>
</tr>
<tr>
<td><input type="text" name="name[]"></td>
<td><input type="radio" name="radio4" value="+">+</td>
<td><input type="radio" name="radio4" value="-">-</td>
</tr>
<tr>
<td><input type="text" name="name[]"></td>
<td><input type="radio" name="radio5" value="+">+</td>
<td><input type="radio" name="radio5" value="-">-</td>
</tr>
</table>
<input type="submit" value="submit">
</form>
</body>
</html>
in the case where the number of rows may vary.
<?php
$rowCount = count($_POST['name']);
echo "<table>";
for ($i=0; $i<$rowCount;$i++)
{
echo "<tr>";
echo "<td>".$_POST['name'][$i-1]."</td>";
echo "<td>".$_POST['radio'.$i]."</td>";
echo "</tr>";
}
echo "</table>"
?>
Get the number of rows by using count() to count an array element present in each row, in this case name="name[]". Then loop through the rows by creating a for loop and inside the for loop get each variable with $_POST. To get the radio value that was selected for each row (i.e. radio1, radio2, etc.), reference the element name not by array but just by name, because if you create an element radio[] different rows will be considered part of the same radio selection group.