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.

PeeHaa
  • 71,436
  • 58
  • 190
  • 262
Interfaith
  • 145
  • 1
  • 2
  • 14

3 Answers3

2

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

$S1Q1 = $_GET['S1Q1'];
($S1Q1 == $correct[0]) ? 'correct' : 'wrong'
Philippe Boissonneault
  • 3,949
  • 3
  • 26
  • 33
  • 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 '12 at 17:45
  • Both single or double quote will work. http://stackoverflow.com/questions/3446216/difference-between-single-quote-and-double-quote-string-in-php – Philippe Boissonneault Sep 14 '12 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 '12 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 – Philippe Boissonneault Sep 14 '12 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'] – Philippe Boissonneault Sep 14 '12 at 18:02
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.

The System Restart
  • 2,873
  • 19
  • 28
  • OP wants to match against `$correct[0]` which isn't an array, but a string. – PeeHaa Sep 14 '12 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. – David Grenier Sep 14 '12 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 '12 at 17:49
1

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

 $S1Q1 = $_POST['S1Q1']
Maks3w
  • 6,014
  • 6
  • 37
  • 42