How can the code snippet be improved to handle multiple correct answers for each question in the PHP quiz?
Currently, the code snippet only allows for one correct answer per question in the PHP quiz. To handle multiple correct answers for each question, we can modify the data structure to store an array of correct answers for each question. This way, we can check if the user's input matches any of the correct answers in the array.
<?php
$quiz = [
[
'question' => 'What is the capital of France?',
'answers' => ['Paris'],
],
[
'question' => 'Which programming language is used for web development?',
'answers' => ['HTML', 'CSS', 'JavaScript'],
],
// Add more questions with multiple correct answers here
];
$score = 0;
foreach ($quiz as $key => $question) {
echo $question['question'] . "\n";
$userAnswer = readline('Your answer: ');
if (in_array($userAnswer, $question['answers'])) {
echo "Correct!\n";
$score++;
} else {
echo "Incorrect. The correct answer(s) is/are: " . implode(', ', $question['answers']) . "\n";
}
}
echo "Your final score is: " . $score . "/" . count($quiz) . "\n";
?>
Related Questions
- What is the function array_diff() used for in PHP and how can it be applied to multidimensional arrays?
- How can PHP developers ensure the compatibility and stability of their code when incorporating new mysqli_ functions alongside existing mysql_ functions in a project?
- What are common pitfalls when using regex for parsing YouTube links in PHP?