What are the best practices for utilizing PHP sessions to ensure unique question outputs in a script?

To ensure unique question outputs in a script using PHP sessions, you can generate a random question identifier and store it in the session. This identifier can then be used to fetch a unique question from a database or an array. By checking if the identifier is already in the session, you can prevent the same question from being displayed multiple times.

<?php
session_start();

// Generate a random question identifier
$question_id = mt_rand(1, 100);

// Check if the identifier is already in the session
if(isset($_SESSION['question_id'])) {
    // Regenerate a new identifier until it is unique
    while($_SESSION['question_id'] == $question_id) {
        $question_id = mt_rand(1, 100);
    }
}

// Store the unique identifier in the session
$_SESSION['question_id'] = $question_id;

// Fetch and display the question based on the identifier
$question = getQuestionFromDatabase($question_id);
echo $question;

function getQuestionFromDatabase($question_id) {
    // Implement your logic to fetch a question from a database or an array
    // Return the question based on the identifier
}
?>