0

Hello I have the following script in PHP:

$correct = array("a", "a", "a", "a");
$totalValue = "First Name: " . $fname . "\n";
$totalValue .= "About Our Mission | Question 01: " . $S1Q1 . "    " . (compare $correct[0] with $S1Q1 choice) ? "Correct" : "Wrong" . "\n";

$S1Q1 is a variable which I accept from a form using radio button:

    <input type="radio" name="S1Q1" value="a" /> True
    <input type="radio" name="S1Q1" value="b" /> False

(compare $correct[0] with $S1Q1 choice) ? "Correct" : "Wrong" < how do I implement that in the php code.

And for the next radio choice I would compare $correct[1] with $S1Q2... and so forth.

1

3 Answers 3

2

This will check if value entered in radio button is = to correct answer

$S1Q1 = $_GET['S1Q1'];
($S1Q1 == $correct[0]) ? 'correct' : 'wrong'
5
  • I forgot to add $S1Q1 = $_POST['S1Q1']; that I already have on the file so this will take care of it. Thanks! and it's within single quote or double?
    – Interfaith
    Sep 14, 2012 at 17:45
  • Both single or double quote will work. stackoverflow.com/questions/3446216/… Sep 14, 2012 at 17:56
  • From below i asked: What if i have multiple variables, S1Q1(Section 1 Question 1). So let's say i have S1Q1 S1Q2 S2Q1 S2Q2 S2Q3 S3Q1 S3Q2 and so forth, how can I check that? would you happen to know?
    – Interfaith
    Sep 14, 2012 at 17:57
  • Try using an array for your questions name="S1[0]", name="S1[1]", name="S2[0]", name="S2[1]" ... then $_POST['S1'] will return array of responses for all questions Sep 14, 2012 at 18:01
  • or you can use name="S[0][0]", name="S[0][1]", name="S[1][0]", name="S[1][1]" then you will only have to get $_POST['S'] Sep 14, 2012 at 18:02
1

You can access to the var with $_POST and/or $_GET

 $S1Q1 = $_POST['S1Q1']
1

Main mechanism:

$S1Q1 = $_GET['S1Q1']; // or $_POST['S1Q1']
($correct[0] == $S1Q1 ) ? 'Correct' : 'Wrong'

Using loop:

if( isset($_POST) && !empty($_POST) ){
   foreach($_POST as $key => $val ) {
       $index = (int) str_replace('S1Q', '', $key ); // 1, 2, 3..
       $result = $val == $correct[ $index - 1 ] ? 'Correct' : 'Wrong';
   }
}

Use $result in you code.

3
  • OP wants to match against $correct[0] which isn't an array, but a string.
    – PeeHaa
    Sep 14, 2012 at 17:41
  • This would check to see if the post is equal to the correct answer for any question. OP wants to check to see if it's equal to one specific question. Sep 14, 2012 at 17:42
  • What if i have multiple variables, S1Q1(Section 1 Question 1). So let's say i have S1Q1 S1Q2 S2Q1 S2Q2 S2Q3 S3Q1 S3Q2 and so forth, how can I check that?
    – Interfaith
    Sep 14, 2012 at 17:49

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.