Last active
May 9, 2019 09:42
-
-
Save markomilivojevic/15f968b276cf9f9b33d0b654044a0f1a to your computer and use it in GitHub Desktop.
PHP array random elements per segments
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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