Databases can handle this kind of logic already.
First initialize the usedQuestion array as empty. Then select a random question from the database:
SELECT * FROM myQuestions
WHERE id
NOT IN () ORDER BY RAND() LIMIT 1
(assuming MySQL)
Check to make sure the query returned a record, in case we reached the end of the database list or we encountered an error of some sort, and store the record id in our array. Then assuming the previous question's id was, let's say, 7
, you'd modify your next query to read:
SELECT * FROM myQuestions
WHERE id
NOT IN (7) ORDER BY RAND() LIMIT 1
Check to make sure the query returned a record, in case we reached the end of the database list or we encountered an error of some sort, and store the record id in our array. Then, joining the array ids together by a comma, assuming our second question's id was 4
, we'd create our next query:
SELECT * FROM myQuestions
WHERE id
NOT IN (7,4) ORDER BY RAND() LIMIT 1
etc.
You could also handle this sort of logic without a fancy query. First, SELECT the number of records in the database and store the number of questions in a variable. Then generate a random number between 1 and that number, and use that as the id to select from the database. If your database ids have gaps in it, you can instead SELECT by taking advantage of LIMIT/OFFSET. For example to select the 3rd record in your database, you'd use LIMIT 2,1 thus offsetting by 2 and limiting to 1.
Next, store your random number result in an array.
Now generate a new random number between 1 and the size of your database minus the size of your array. Then loop through your array, if the random number you picked exists in the array, add one then start the loop from the beginning and add one for each time the number exists in the array. Finally, you'll have your 2nd number ready. Store the modified number in your array rather than the result of the random function and select its id from the database. For example, let's say you had 8 records in your database:
1,2,3,4,5,6,7,8
First you'd generate a random number integer from 1-8.
Let's say the result was 7. You'd store it in your array and select the 7th record in the database. Then you'd generate a random integer from 1-7, let's say 7 popped up again, you'd loop through the array and see 7 was already in there, so you'd add 1 and reloop the array. Since 8 isn't in the array, you'd store it in the array and select the 8th record in the database. So far we've selected the 2 end records from the database at random. Then we'd generate a random number 1-6 let's say it was 1 so we'd store it into your array and select the 1st record from the database. Our array now reads: [1,7,8]
. Then we'd generate a random number 1-5. Let's say we ended up on 1 again. We'd see 1 is already in our array so we'd add 1. So we'd select the 2nd record from the database and store 2 in the array. Etc.