$answers = array("a", "b", "c", "a", "a", "a");
$S1Q1 = $_POST['S1Q1'];
$S1Q2 = $_POST['S1Q2'];
$S2Q1 = $_POST['S2Q1'];
$S2Q2 = $_POST['S2Q2'];
$S2Q3 = $_POST['S2Q3'];
$S2Q4 = $_POST['S2Q4'];
$totalValue .= "About OM | Question 01: " . $S1Q1 . " " . ($S1Q1 == $correct[0]) ? 'Correct' : 'Wrong' . "\n";
$totalValue .= " | Question 02: " . $S1Q2 . " " . ($S1Q2 == $correct[1]) ? 'Correct' : 'Wrong' . "\n\n";
$totalValue .= "About EHS | Question 01: " . $S2Q1 . " " . ($S2Q1 == $answers[2]) ? 'Correct' : 'Wrong' . "\n";
$totalValue .= " | Question 02: " . $S2Q2 . " " . ($S2Q2 == $answers[3]) ? 'Correct' : 'Wrong' . "\n";
$totalValue .= " | Question 03: " . $S2Q3 . " " . ($S2Q2 == $answers[4]) ? 'Correct' : 'Wrong' . "\n";
$totalValue .= " | Question 04: " . $S2Q4 . " " . ($S2Q2 == $answers[5]) ? 'Correct' : 'Wrong' . "\n\n";
I have the above php script, what method or function can I use to calculate how many Correct and how many Wrong the user has in a loop and then calculate percentage?
Example:
Correct: 4
Wrong: 2
Total: 6
Percentage Correct: ((4/6) * 100) =
66.666666666% => round it to 66%
Here is a quick and dirty way to accomplish it without changing what you already have:
That said, I think this could be done much better. I would pass the variables in as an array. Your post string would look something like this:
This would be received by PHP like this:
Take a look at this example. It looks a bit longer and perhaps a bit more complicated, but it is much more flexible and expandable. If you need to add any questions, answers, etc…all you have to do is add the corresponding array entry. In the long run, I think you will be much happier with that.