I have an array of 30 values and I need to extract from this array 3 different random values. How can I do it?
相关问题
- Views base64 encoded blob in HTML with PHP
- Laravel Option Select - Default Issue
- PHP Recursively File Folder Scan Sorted by Modific
- Can php detect if javascript is on or not?
- Using similar_text and strpos together
I'm not sure why bother using
array_rand()
at all as it's just an extra function call for seemingly no reason. Simplyshuffle()
and slice the first three elements:use
shuffle($array)
thenarray_rand($array,3)
Shamelessly stolen from the PHP manual:
http://us2.php.net/array_rand
Note that, as of PHP 5.2.10, you may want to shuffle (randomize) the keys that are returned via
shuffle($rand_keys)
, otherwise they will always be in order (smallest index first). That is, in the above example, you could get "Neo, Trinity" but never "Trinity, Neo."If the order of the random elements is not important, then the above code is sufficient.