Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /**
- * Get random elements by segments
- *
- * If you pass 100 elements with limit 5, it will return 5 elements in following order:
- *
- * First: rand between 0 - 20
- * Second: rand between 20 - 40
- * Third: rand between 40 - 60
- * Fourth: rand between 60 - 80
- * Fifth: rand between 80 - 100
- *
- * @param array $elements
- * @param int $limit
- * @return array
- */
- public static function arrayRandSegmented(array $elements, int $limit): array
- {
- $randomElements = [];
- $itemsCount = count($elements);
- if ($itemsCount && $limit < $itemsCount) {
- $elements = array_values($elements);
- $step = intval($itemsCount / $limit);
- for ($i = 0; $i < $limit; $i++) {
- $currentOffset = $i * $step;
- $randomIndex = rand($currentOffset, $currentOffset + $limit - 1);
- $randomElements[$randomIndex] = $elements[$randomIndex];
- }
- }
- return $randomElements;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement