Created
July 29, 2022 18:11
-
-
Save yuheiy/2f0b0af29a8afb85387fc9d4669b2998 to your computer and use it in GitHub Desktop.
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 | |
// Implementation like lodash’s `sampleSize()` | |
// https://lodash.com/docs/4.17.15#sampleSize | |
function array_sample_size(array $array, int $size = 1) | |
{ | |
$size = min($size, count($array)); | |
$keys = array_rand($array, $size); | |
if (!is_array($keys)) { | |
$keys = [$keys]; | |
} | |
$result = []; | |
foreach ($keys as $key) { | |
$result[] = $array[$key]; | |
} | |
return $result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment