KKL
KKL

Reputation: 33

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?

Upvotes: 3

Views: 2118

Answers (2)

Phillip
Phillip

Reputation: 1

¿shuffle associative array? This worked for me:

 function shuffle_assoc($array) {
    $keys = array_keys($array);
    shuffle($keys);
    foreach($keys as $key) {
        $new[$key] = $array[$key];
    }
    return $new;
}

Use:

Print_r(shuffle_assoc($my_array));

Input:

$my_array = Array
                (
                  [Nicaragua] => 62
                  [Mexico] => 50
                  [France] => 23
                 )

Output:

Array
(
    [France] => 23
    [Nicaragua] => 62
    [Mexico] => 50
)

Upvotes: 0

John Conde
John Conde

Reputation: 219804

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"

Upvotes: 4

Related Questions