tags:

views:

41

answers:

4

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!

+4  A: 

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

Chad Birch
So whats the point of shuffling it if its going to just return true/false?
mike
I don't think you're understanding. It shuffles *in place*. If you printed out `$array1` instead of `$array2` in your code you would have gotten a shuffled version.
Chad Birch
You're right. I didn't understand. Makes perfect sense! Thanks!
mike
+1  A: 

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

Col. Shrapnel
+1  A: 

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.

Sinan
+1  A: 
$array2 = $array1;
shuffle($array2);
print_r($array2);
Ivo Sabev