php测验显示正确的数量和错误答案的数量

时间:2012-05-07 10:45:01

标签: php if-statement counter

我有一个php页面,有多个选择测验问题,比如这个

<p>1. Is Manhattan near New York?<br>
    <input type="radio" name="ans1" value="3">
    Yes<br>
    <input type="radio" name="ans1" value="2">
    Maybe<br>
    <input type="radio" name="ans1" value="1">
    No</p>
  <p>2. Do you like Indian food?<br>
    <input type="radio" name="ans2" value="1">
    Some times<br>
    <input type="radio" name="ans2" value="3">
    Never<br>
    <input type="radio" name="ans2" value="2">
    Always</p>

该页面会自行发布并检查答案是否正确,如此

if($ans1 == "3") { 
$test_complete .="Question one is <span class='green'>correct</span>, well done!<br/>";  
}else{ 
$test_complete .="Question one is <span class='red'>incorrect</span>!<br/>"; 
} 
// change the quest2 to the right answer
if($ans2 == "2") { 
$test_complete .="Question two is <span class='green'>correct</span>, well done!<br/>"; 
}else{ 
$test_complete .="Question two is <span class='red'>incorrect</span>!<br/>"; 
}

现在我没有告诉用户答案中的一个或两个是正确的,我想运行一个计数器来计算正确的数量和错误答案的数量,并将其显示在两个表格框中,同时显示一个框的总数的问题。

3 个答案:

答案 0 :(得分:1)

喜欢这个......?

$result = $ans1 == 3;
$result += $ans2 == 2;
$result += $ans3 == 1;

echo "You got $result/3 questions right";

http://codepad.org/6zBQXQIT

答案 1 :(得分:1)

有多种方法可以做到这一点。我会有一系列对应问题的正确问题然后进行比较。例如:

$correct_answers = array('3', '2');
for ($i = 0; $i < $number_of_questions; $i++)
{
   $ans_var = 'ans'.$i;
   if ($_POST[$ans_var] == $correct_answers[$i])
   {
      $score++;
   }
}

答案 2 :(得分:0)

如果我正确理解了这个问题......

session_start();
if (!isset($_SESSION['total'])){$_SESSION['total']=0;}
if (!isset($_SESSION['correct'])){$_SESSION['correct']=0;}
if($ans1 == "3") {$_SESSION['correct']+=1;}
if($ans2 == "2") {$_SESSION['correct']+=1;}
if (isset($ans1) || isset($ans2)) {$_SESSION['total']+=1}
echo '<table><tr><td>Correct answers:</td><td>'.$_SESSION['correct'].'</td></tr>';
echo '<tr><td>Wrong answers:</td><td>'.$_SESSION['total']-$_SESSION['correct'].'</td></tr>';
echo '<tr><td>Total answers</td><td>'.$_SESSION['total'].'</td></tr></table>';