Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static function randomElements(array $array = array('a', 'b', 'c'), $count = 1, $allowDuplicates = false)
- {
- $allKeys = array_keys($array);
- $numKeys = count($allKeys);
- if (!$allowDuplicates && $numKeys < $count) {
- throw new \LengthException(sprintf('Cannot get %d elements, only %d in array', $count, $numKeys));
- }
- $highKey = $numKeys - 1;
- $keys = $elements = array();
- $numElements = 0;
- while ($numElements < $count) {
- $num = mt_rand(0, $highKey);
- if (!$allowDuplicates) {
- if (isset($keys[$num])) {
- continue;
- }
- $keys[$num] = true;
- }
- $elements[] = $array[$allKeys[$num]];
- $numElements++;
- }
- return $elements;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement