include '../db.php';
$sql = "SELECT question, rightans, ans2, ans3, ans4, id, subject, author FROM others WHERE subject = '".$sub."'";
$result = $con->query($sql);
$question=array();
if ($result->num_rows > 0) {
$x=0;
while($row = $result->fetch_assoc()) {
if ($row['question']!=""){
$question[$x]=$row['question'];
$x=$x+1;
}
}}
$random_keys=array_rand($question,20);
$rd=count($random_keys);
$con->close();
$z=array();
for ($y = 0; $y <= $rd; $y++) {
echo $question[$random_keys[$y]];
}
Technically I should be receiving 20 random questions. But i am only getting the first one.
I had checked that $y value, it is increasing and $question[$random_keys[1]] and $question[$random_keys[2]] are also returing the expected values.
But for some reason $question[$random_keys[$y]] is functioning like $question[$random_keys[0]] only? what went wrong?
>Solution :
If you just want 20 questions from a list of questions, then you can try this method.
<?php
$question = array(
"Question 1",
"Question 2",
"Question 3",
"Question 4",
"Question 5",
"Question 6",
"Question 7",
"Question 8",
"Question 9",
"Question 10",
"Question 11",
"Question 12",
"Question 13",
"Question 14",
"Question 15",
"Question 16",
"Question 17",
"Question 18",
"Question 19",
"Question 20",
"Question 21",
"Question 22",
"Question 23",
"Question 24",
"Question 25"
);
shuffle($question);
$rand_questions = array_slice($question,0,20);
foreach($rand_questions as $question){
echo $question."<br>";
}