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);
}
>Solution :
If recursion is not required, you could create a one-liner where you give a max value and a count.
$randomSize = fn($size, $max) => array_map(fn($max) => random_int(0, $max), range(1, $size));
print_r($randomSize(20, 10));
Output
20 values from 0-10
Array
(
[0] => 0
[1] => 1
[2] => 3
[3] => 4
[4] => 2
[5] => 0
[6] => 4
[7] => 0
[8] => 2
[9] => 7
[10] => 7
[11] => 3
[12] => 10
[13] => 4
[14] => 8
[15] => 1
[16] => 3
[17] => 5
[18] => 10
[19] => 3
)