CarlRyds
CarlRyds

Reputation: 217

Random radio buttons PHP

I have these radio buttons...

<div class="radio"><label><input type="radio" name="1" id="1" value="0"><?php echo $incorrect1; ?></label></div>
<div class="radio"><label><input type="radio" name="2" id="2" value="0"><?php echo $incorrect2; ?></label></div>
<div class="radio"><label><input type="radio" name="3" id="3" value="1"><?php echo $correct; ?></label></div>  

Id like them to display in different orders randomly, how wuld i do that in php? Thanks

PHP

$object2 = new ConnectToDB();
$result2 = $object2->getQue($ksGet,$contIDGet);

foreach($result2 as $row){

    $question .= "" . $row['question'] . ""; 
    $incorrect1 .= "" . $row['incorrect1'] . "";
    $incorrect2 .= "" . $row['incorrect2'] . "";
    $correct .= "" . $row['correct'] . ""; 

}

Upvotes: 1

Views: 1174

Answers (2)

Sulthan Allaudeen
Sulthan Allaudeen

Reputation: 11310

Though it is quite long, I would like make this answer to teach how rand and if else works to my Team :p

Step 1 :

I declared the three radio box to 3 variable named as $first, $second and $third

Step 2 :

Generate Random number between 1 and 3 $case = rand(1,3);

Step 3 :

Put it in a if-else case

<?php

$first = '<div class="radio"><label><input type="radio" name="1" id="1" value="0"><?php echo $incorrect1; ?></label></div>';
$second = '<div class="radio"><label><input type="radio" name="2" id="2" value="0"><?php echo $incorrect2; ?></label></div>';
$third = '<div class="radio"><label><input type="radio" name="3" id="3" value="1"><?php echo $correct; ?></label></div>';
$case = rand(1, 3);
if ($case == 1) {
    echo $first;
    echo $second;
    echo $third;
} elseif ($case == 2) {
    echo $second;
    echo $first;
    echo $third;
} else {
    echo $third;
    echo $first;
    echo $second;
}
?>

Upvotes: 2

Dimitar Ivanov
Dimitar Ivanov

Reputation: 76

$answer1=\"<div class=\"radio\"><label><input type=\"radio\" name=\"1\" id=\"1\" value=\"0\">$incorrect1</label></div>
";
$answer2="<div class=\"radio\"><label><input type=\"radio\" name=\"2\" id=\"2\" value=\"0\">$incorrect2</label></div>
";
$answer3="<div class=\"radio\"><label><input type=\"radio\" name=\"3\" id=\"3\" value=\"1\">$correct</label></div>
";
$rand=rand(1,3);
switch($rand){
case 1:
$answers.=$answer3.$answer1.$answer2;
break;
case 2:
$answers.=$answer2.$answer3.$answer1;
break;
case 3:
$answers.=$answer1.$answer2.$answer3;
break;
}

Upvotes: 0

Related Questions