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>";
    }
}
?>