Code below separates correct letters and incorrect letters from each other if option type is letter. E.g If option type is A-D and correct letter is B, then it removes B from A B C D using the $wrong variable making it A C D for $incorrect_ans variable.
Now what I want to do is that if option type is Yes or No and correct answer is Yes, then it should separate Yes from Yes, No so that I can display No in incorrect_ans variable. Problem is that at the moment it is not split both these options, so it is displaying bother this answers as incorrect answers when in this example No should be incorrect. But how can this be achieved?
I want the same to work for True or False option as well. As I mentioned my code works for letter answers, just not Yes or No or True or False.
Below is code:
$specialOptionTypes = array(
'Yes or No' => array('Yes', 'No'),
'True or False' => array('True', 'False')
);
while ($stmt->fetch()) {
// Do this for each row:
if (array_key_exists($dbOptionType, $specialOptionTypes)) {
$options = $specialOptionTypes[$dbOptionType];
} else if (preg_match('/^([A-Z])-([A-Z])$/', $dbOptionType, $match)) {
$options = range($match[1], $match[2]);
} else {
// issue warning about unrecognized option type
$options = array();
}
$right = $dbAnswer; // $right = 'True';
$wrong = array_diff($options, $right);
$incorrect_ans[] = $wrong;
}
UPDATE:
If I had this data in database
Question Table:
QuestionId QuestionNo OptionId
11 1 3
12 2 26
Option_Table Table:
OptionId OptionType
1 A-C
2 A-D
3 A-E
..............
26 Yes or No
Answer Table:
AnswerId Answer QustionId
1 A 11
2 C 11
3 Yes 12
Ok so for Question 1 (look at tables closely), The option type ($OptionType) is A-E meaning by using code below:
(preg_match('/^([A-Z])-([A-Z])$/', $dbOptionType, $match)) {
$options = range($match[1], $match[2]);
It displays these Options A B C D E.
Now Correct Answers for Question 1 is A and C (using $right = $dbAnswer;). So Split correct answers from incorrect answers using:
$wrong = array_diff($options, $right);
Then we are left with the incorrect answers which as B D E. These are stored in array using:
$incorrect_ans[] = $wrong;
Problem I have is that this does not work for Yes or No option in question 2. The incorrect answer is No and correct answer is Yes for question 2 but it does not split Yes and No as it displays them both as incorrect answers. This is incorrect.
Update your code a bit
The
array_diffneed both param be array. You can alsovar_dumpthe$optionvariable to be sure that it contains the right data.Of course, the final
$incorrect_ansarray can contains both ‘Yes’ and ‘No’ because each is added when you fetch each row. Each element of$incorrect_anscontains the wrong answers of the question it parsed from . I think you should use the question ID as the key ob the$incorrect_ans, not just use the default numerical key.