What are some best practices for structuring PHP code when creating a quiz with multiple questions and answers?

When creating a quiz with multiple questions and answers in PHP, it is best to organize your code in a structured and modular way to make it easier to manage and maintain. One approach is to use arrays to store the questions and answers, making it simple to add, remove, or modify quiz content. Additionally, separating the logic for displaying questions, collecting answers, and calculating scores into different functions can help improve code readability and reusability.

// Define an array to store quiz questions and answers
$quiz = [
    [
        'question' => 'What is the capital of France?',
        'answers' => ['Paris', 'London', 'Berlin', 'Madrid'],
        'correct_answer' => 'Paris'
    ],
    [
        'question' => 'What is the largest mammal?',
        'answers' => ['Elephant', 'Blue whale', 'Giraffe', 'Hippopotamus'],
        'correct_answer' => 'Blue whale'
    ],
    // Add more questions as needed
];

// Function to display a question
function displayQuestion($question) {
    echo $question['question'] . "\n";
    foreach ($question['answers'] as $answer) {
        echo "- $answer\n";
    }
}

// Function to check the answer
function checkAnswer($question, $user_answer) {
    return $user_answer === $question['correct_answer'];
}

// Example usage
foreach ($quiz as $key => $question) {
    displayQuestion($question);
    $user_answer = readline('Your answer: ');
    if (checkAnswer($question, $user_answer)) {
        echo "Correct!\n";
    } else {
        echo "Incorrect. The correct answer is: {$question['correct_answer']}\n";
    }
}