Skip to content

Instantly share code, notes, and snippets.

@yuheiy
Created July 29, 2022 18:11
Show Gist options
  • Save yuheiy/2f0b0af29a8afb85387fc9d4669b2998 to your computer and use it in GitHub Desktop.
Save yuheiy/2f0b0af29a8afb85387fc9d4669b2998 to your computer and use it in GitHub Desktop.
<?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