How can sessions be used in PHP to keep track of which questions have been answered by a user in a quiz?
To keep track of which questions have been answered by a user in a quiz using sessions in PHP, you can store an array of answered question IDs in the session variable. Each time a user answers a question, you can add the question ID to this array. This way, you can easily check if a question has been answered by checking if its ID is present in the array stored in the session.
session_start();
// Check if the user has answered any questions before
if (!isset($_SESSION['answered_questions'])) {
$_SESSION['answered_questions'] = [];
}
// Add the ID of the answered question to the array
$answeredQuestionId = 1; // ID of the answered question
$_SESSION['answered_questions'][] = $answeredQuestionId;
// Check if a specific question has been answered
$questionIdToCheck = 1; // ID of the question to check
if (in_array($questionIdToCheck, $_SESSION['answered_questions'])) {
echo "Question $questionIdToCheck has been answered.";
} else {
echo "Question $questionIdToCheck has not been answered yet.";
}