Skip to content

Instantly share code, notes, and snippets.

@markomilivojevic
Last active May 9, 2019 09:42
Show Gist options
  • Save markomilivojevic/15f968b276cf9f9b33d0b654044a0f1a to your computer and use it in GitHub Desktop.
Save markomilivojevic/15f968b276cf9f9b33d0b654044a0f1a to your computer and use it in GitHub Desktop.
PHP array random elements per segments
<?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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment