Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

shuffle() doesn't work as expected with an associative array

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?

like image 331
KKL Avatar asked Jun 28 '26 12:06

KKL


1 Answers

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"

like image 84
John Conde Avatar answered Jul 01 '26 03:07

John Conde