<?php
/**
* Wraps array_rand call with additional checks
*
* TLDR; not so radom as you'd wish.
*
* NOTICE: the closer you get to the input arrays length, for the n parameter, the output gets less random.
* e.g.: array_random($a, count($a)) == $a will yield true
* This, most certainly, has to do with the method used for making the array random (see other comments).
*
* @throws OutOfBoundsException - if n less than one or exceeds size of input array
*
* @param array $array - array to randomize
* @param int $n - how many elements to return
* @return array
*/
function array_random(array $array, int $n = 1): array
{
if ($n < 1 || $n > count($array)) {
throw new OutOfBoundsException();
}
return ($n !== 1)
? array_values(array_intersect_key($array, array_flip(array_rand($array, $n))))
: array($array[array_rand($array)]);
}