I want to do a quiz and here is my array:
$questions = array("1+1"=>2,"5+2"=>7,"5+9"=>14,"3+5"=>8,"4+6"=>10,"1+8"=>9,"2+7"=>9,
"6+7"=>13,"9+3"=>12,"8+2"=>10,"5+5"=>10,"6+8"=>14,"9+4"=>13,"7+8"=>15,
"8+9"=>17,"4+8"=>12,"7+1"=>8,"6+3"=>9,"2+5"=>7,"3+4"=>7);
shuffle($questions);
foreach($questions as $key => $value) {
echo $key.' ';
}
However, from the above code, I get the output like the following:
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 //Wrong!
Why do I get this output? I want to get every questions. How should I get it?
From the manual for shuffle() (emphasis mine):
Note: This function assigns new keys to the elements in array. It will remove any existing keys that may have been assigned, rather than just reordering the keys.
Here's a solution for associative arrays from the comments of that page:
function shuffle_assoc(&$array) {
$keys = array_keys($array);
shuffle($keys);
foreach($keys as $key) {
$new[$key] = $array[$key];
}
$array = $new;
return true;
}
Credits goes to: "ahmad at ahmadnassri dot com"
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