Advertisement
Guest User

Untitled

a guest
May 19th, 2019
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.91 KB | None | 0 0
  1. <?php
  2.  
  3. /**
  4. * Get random elements by segments
  5. *
  6. * If you pass 100 elements with limit 5, it will return 5 elements in following order:
  7. *
  8. * First: rand between 0 - 20
  9. * Second: rand between 20 - 40
  10. * Third: rand between 40 - 60
  11. * Fourth: rand between 60 - 80
  12. * Fifth: rand between 80 - 100
  13. *
  14. * @param array $elements
  15. * @param int $limit
  16. * @return array
  17. */
  18. public static function arrayRandSegmented(array $elements, int $limit): array
  19. {
  20. $randomElements = [];
  21.  
  22. $itemsCount = count($elements);
  23. if ($itemsCount && $limit < $itemsCount) {
  24. $elements = array_values($elements);
  25. $step = intval($itemsCount / $limit);
  26. for ($i = 0; $i < $limit; $i++) {
  27. $currentOffset = $i * $step;
  28. $randomIndex = rand($currentOffset, $currentOffset + $limit - 1);
  29.  
  30. $randomElements[$randomIndex] = $elements[$randomIndex];
  31. }
  32. }
  33.  
  34. return $randomElements;
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement