Advertisement
Guest User

Untitled

a guest
Dec 11th, 2017
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.86 KB | None | 0 0
  1. public static function randomElements(array $array = array('a', 'b', 'c'), $count = 1, $allowDuplicates = false)
  2. {
  3. $allKeys = array_keys($array);
  4. $numKeys = count($allKeys);
  5.  
  6. if (!$allowDuplicates && $numKeys < $count) {
  7. throw new \LengthException(sprintf('Cannot get %d elements, only %d in array', $count, $numKeys));
  8. }
  9.  
  10. $highKey = $numKeys - 1;
  11. $keys = $elements = array();
  12. $numElements = 0;
  13.  
  14. while ($numElements < $count) {
  15. $num = mt_rand(0, $highKey);
  16.  
  17. if (!$allowDuplicates) {
  18. if (isset($keys[$num])) {
  19. continue;
  20. }
  21. $keys[$num] = true;
  22. }
  23.  
  24. $elements[] = $array[$allKeys[$num]];
  25. $numElements++;
  26. }
  27.  
  28. return $elements;
  29. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement