mike
mike

Reputation: 8141

php shuffle() returns one item

Anyone have any idea why shuffle() would only return 1 item?

when using:

$array2 = shuffle($array1);

with the following array($array1):

Array
(
    [0] => 1
    [1] => 5
    [2] => 6
    [3] => 7
    [4] => 8
    [5] => 10
    [6] => 11
    [7] => 12
    [8] => 13
    [9] => 14
)

The output of:

print_r($array2);

is simply: 1

Any idea as to why it would not only not shuffle the array, but knock off the remaining 9 items in the array?

thanks!

Upvotes: 2

Views: 3696

Answers (4)

Ivo Sabev
Ivo Sabev

Reputation: 5240

$array2 = $array1;
shuffle($array2);
print_r($array2);

Upvotes: 1

Sinan
Sinan

Reputation: 5980

shuffle changes the original array. So in your case the shuffled array is $array1.

$array2 is simply a boolean value. The function returns true or false.

Upvotes: 2

Your Common Sense
Your Common Sense

Reputation: 157941

Please read a function description before use http://php.net/shuffle it may work other than you expect.

Upvotes: 1

Chad Birch
Chad Birch

Reputation: 74608

shuffle() shuffles the array in place, and returns true if it succeeded. If you want $array2 to be a shuffled version of $array1, first make it a copy of $array1 and then call shuffle($array2);

See the docs: shuffle

Upvotes: 7

Related Questions