Diksha Diksha -4 years ago 50
PHP Question

Radio button set's array created dynamically with echo in php. How to get their values?

I've created a php page which retrieves question and options(as MCQ's) from the database and in that Radio buttons are created dynamically using


The name for each radio button group is assigned into an array from which one by one index's value is set to the

$numrows=mysqli_num_rows($result);//gets the number of questions

for($i=0;$i<$numrows;$i++){ //creating array of names for each set of radio buttons
while(($myrow=mysqli_fetch_array($result)) && ($i<$numrows)){
echo $myrow["q_no"].". ";
echo $myrow["ques"]."<br><br>";
echo "<input type='radio' name='$radiogrp_name[$i]' value='a'/>".$myrow["A"]."<br>";
echo "<input type='radio' name='$radiogrp_name[$i]' value='b'/>".$myrow["B"]."<br>";
echo "<input type='radio' name='$radiogrp_name[$i]' value='c'/>".$myrow["C"]."<br>";
echo "<input type='radio' name='$radiogrp_name[$i]' value='d'/>".$myrow["D"]."<br><br><br>";

How would I get the selected radio buttons and set them into a
variable? Can anyone help with this? Or any other way to implement this?
Thank you in advance!

Answer Source

On the page that the form is POST'ed to you are going to need to look through the $_POST array and strip out the relevant answers. Ideally you would have a list of expected indexes to drive that page, but if not you could just try to pattern match the indexes.

Something like:

$results = array();
foreach($_POST as $key => $value){
    if(preg_match("/q(\d{1,3})/", $key, $matches)){
        $results[$matches[1]] = $value;

results would then contain an array of values indexed by the numeral in name="q#" and you would just set it to the session or do with it whatever you need.

EDIT by the way, you'll need to wrap your string inclusion in curlies since it is an array.

echo "<input type='radio' name='{$radiogrp_name[$i]}' value='d'/>"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download