开发者

PHP difference between shuffle and array_rand

What exactly is the difference between shuffle and a开发者_StackOverflowrray_rand functions in PHP? Which is faster if there is no difference.

Thanks


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 keys 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.


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.


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.


By changing $no parameter I tried following code snippet to test performances of both function. Even in big arrays there is no much differrence. Most of the the time between 1x10-5 seconds and 5x10-5

$time_start = microtime(true);
$rand_keys = array_rand($myArray, $no);
echo (microtime(true)-$time_start)."\n";

$time_start = microtime(true);
shuffle($myArray);
echo (microtime(true)-$time_start)."\n";


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]).


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

array_rand leaves the original array intact and has an optional parameter to allow you to select the number of elements you wish to return.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜