Search code examples
phparraysrefresh

How to not shuffle array after submitting or refreshing page in PHP


I have an array like this:

$aTotalQuestions = range(1, 10);
shuffle($aTotalQuestions);

This is what I am doing with my array:

echo "<table>";
foreach($aTotalQuestions as $total) {
    echo "<tr><td>$total</td></tr>";
}
echo "</table>";

output for example:

4
5
8
6
1
2
10
9
3
7

Every time when I press a submit button or refresh my page, it is shuffling my array again. I don't want to shuffle my array after another page refresh, but I dont know how to do that.


Solution

  • You need to save shuffle array, eg. in session.

    session_start();
    if (!isset($_SESSION['shuffled'])) {
        $_SESSION['shuffled'] = range(1, 10);
        shuffle($_SESSION['shuffled']);
    }
    
    echo "<table>";
    foreach($_SESSION['shuffled'] as $total) {
        echo "<tr><td>$total</td></tr>";
    }
    echo "</table>";