How can PHP be optimized to ensure that the correct answers are displayed for each question in a quiz form?
To ensure that the correct answers are displayed for each question in a quiz form, you can create an array that stores the correct answers for each question. Then, when displaying the quiz questions, you can check the user's selected answer against the correct answer in the array to determine if it is correct or not.
<?php
// Array to store correct answers for each question
$correctAnswers = array(
1 => 'A',
2 => 'B',
3 => 'C'
);
// Display quiz questions
foreach ($quizQuestions as $questionNumber => $question) {
echo "<p>$questionNumber. $question</p>";
// Check if user's answer is correct
if ($_POST['answer' . $questionNumber] == $correctAnswers[$questionNumber]) {
echo "<p>Your answer is correct!</p>";
} else {
echo "<p>Sorry, your answer is incorrect. The correct answer is: " . $correctAnswers[$questionNumber] . "</p>";
}
}
?>
Related Questions
- How can PHP scripts be structured to separate HTML output from PHP actions, ensuring a cleaner and more secure codebase?
- What potential issues can arise when using file_get_contents in a PHP script, as seen in the provided code snippet?
- How can the issue of replacing the same placeholder in every email be avoided in this PHP script?