void shuffle ( array input)
mixed array_rand ( array input [, int num_req])
Shuffle() takes the entire array and randomises the position of the elements in there. In earlier versions of PHP the shuffle() algorithm was not very good, leading the "randomisation" to be quite weak, however that problem is now fixed.
Take a look at this example:
<?php
$natural_born_killers = array("lions", "tigers", "bears", "kittens");
shuffle($natural_born_killers);
var_dump($natural_born_killers); ?>
If you want to pick out just one random value from an array, you can use array_rand() - it takes an array to read from, then returns one random key from inside there. The advantage to array_rand() is that it leaves the original array intact - you can use the random key returned to grab the related value from the array, but other than that the original array is left untouched.
Array_rand() has an optional second parameter that allows you to specify the number of elements you would like returned. These are each chosen randomly from the array, and are not necessarily returned in any particular order.
Before I show you an example, you need to be aware of the following attributes of array_rand():
-
It returns the keys in your array. If these aren't specified, the
default integer indexes are used. To get the value out of the array,
just look up the value at the key.
-
If you ask for one random element, or do not specify parameter two, you will get a standard variable back.
-
If you ask for more than one random element, you will receive an array of variables back.
-
If you ask for more random elements than there are in the array you will get an error
-
Array_rand() will not return duplicate elements if you request more than one random element
- If you want to read most or all of the elements from your array in a random order, use a mass-randomiser like shuffle() - it is faster.
- With that in mind, here's an example of array_rand() in action:
<?php
$natural_born_killers = array("lions", "tigers", "bears", "kittens");
var_dump(array_rand($natural_born_killers, 2)); ?>
Không có nhận xét nào:
Đăng nhận xét