views:

120

answers:

5

Hi,

What exactly is the difference between shuffle and array_rand functions in PHP? Which is faster if there is no difference.

Thanks

+5  A: 

When called on an array, shuffle randomizes the order of all elements of that array.

For example, the following portion of code :

$arr = array(1, 2, 3, 4, 5);
shuffle($arr);
var_dump($arr);

Could give this output :

array
  0 => int 3
  1 => int 1
  2 => int 5
  3 => int 4
  4 => int 2

The whole array itself gets modified.


When called on an array, array_rand returns one or more elements from that array, randomly selected.

For example, the following portion of code :

$arr = array(1, 2, 3, 4, 5);
$randomly_selected = array_rand($arr, 3);
var_dump($randomly_selected);

Could give tis kind of output :

array
  0 => int 0
  1 => int 2
  2 => int 3

A sub-array of the initial array is returned -- and the initial array is not modified.

Pascal MARTIN
+1  A: 

Shuffle affects the array keys and uses its parameter by reference. Shuffle used to be weak in terms of randomisation in older versions of PHP but that is no longer true.

Array_rand leaves the original array in tact and has an optional parameter to allow you to select the number of elements you wish to return.

Gazler
+1  A: 

shuffle re-orders an array in a random order. this function takes an array by reference, because it is mutating the internal structure of the array, not only accessing it, while array_rand simply returns a random index in an array.

Jacob Relkin
+1  A: 

shuffle changes the order of an array's elements. It's a sorting function.

array_rand returns n (arguments[1], defaults to 1) random elements from the array. It returns a key (for arguments[1] == 1) or an array of keys (for arguments[1] > 1) which reference the elements of the array (arguments[0]).

eyelidlessness
+1  A: 

Shuffle() takes the entire array and randomises the position of the elements in it. [Note: In earlier versions of PHP the shuffle() algorithm was quite poor]

array_rand() takes an array and returns one or more randomly selected entries. The advantage to array_rand() is that it leaves the original array intact.

Mitch Wheat