I am running a quiz making website. I wish to show the answers to a question to a user in a shuffled order.
I'm trying to avoid storing the order that answers were presented to the user, if I were to shuffle them randomly.
I want to shuffle the answers predictably, so that I can repeat the shuffle in the same way later (when displaying results).
I've thought that I could shuffle the list of answers by a certain number (either using the number within the sort, or having multiple types of sorts identifiable by an ID number. This way I can simply store the number that they were shuffled by and recall that number to reshuffle them again to the same order.
Here's the skeleton of what I have so far, but I don't have any logic to put the answers back in the $shuffled_array in the shuffled order.
<?php
function SortQuestions($answers, $sort_id)
{
// Blank array for newly shuffled answer order
$shuffled_answers = array();
// Get the number of answers to sort
$answer_count = count($questions);
// Loop through each answer and put them into the array by the $sort_id
foreach ($answers AS $answer_id => $answer)
{
// Logic here for sorting answers, by the $sort_id
// Putting the result in to $shuffled_answers
}
// Return the shuffled answers
return $shuffled_answers;
}
// Define an array of answers and their ID numbers as the key
$answers = array("1" => "A1", "2" => "A2", "3" => "A3", "4" => "A4", "5" => "A5");
// Do the sort by the number 5
SortQuestions($answers, 5);
?>
Is there technique that I can use to shuffle the answers by the number passed into the function?
PHP's shuffle function uses the random seed given with srand, so you can set a specific random seed for this.
Also, the shuffle method change's the array keys, but this is probably not the best outcome for you, so you may use a different shuffle function:
function shuffle_assoc(&$array, $random_seed) {
srand($random_seed);
$keys = array_keys($array);
shuffle($keys);
foreach($keys as $key) {
$new[$key] = $array[$key];
}
$array = $new;
return true;
}
This function will keep the original keys, but with a different order.
You could rotate the array by a factor.
$factor = 5;
$numbers = array(1,2,3,4);
for ( $i = 0; $i < $factor; $i++ ) {
array_push($numbers, array_shift($numbers));
}
print_r($numbers);
The factor can be randomized, and a function can switch the array back in place, by rotation the other way around.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With