SHARE
TWEET

Untitled

a guest May 19th, 2019 58 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  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. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top