Is there any way I can write a function that only takes $size as an argument and returns an array with $size random values?
My approach so far using an initial array as parameter:
function rand_vector (array $arr, int $size): array {
if (count($arr) == $size) return $arr;
array_push($arr, random_int(0, 30));
return rand_vector ($arr, $size);
}
2
Answers
If recursion is not required, you could create a one-liner where you give a max value and a count.
Output
20 values from 0-10
Instead of comparing the input array to
$size
for the base case, use$size=0
as the base. Then you subtract 1 from$size
when making the recursive calls. The function then generates one random number and pushes it onto the array returned by the recursive call.