I'm making a small function in PHP that, like described in the title, need an array filled with random numbers inside a specified range, the numbers MUST repeat within it. As an example, filling an array with 20 random numbers between 1 and 10 should result in something like this:
Array = [2,5,8,2,8,5,3,9,6,3,4,6,3,1,2,1,2,3,7,1]
CodePudding user response:
This code creates an array ($arr = array();
) and then 20 times (the loop) pushes a random value on the end of the array.
The values are generated by random_int
function that generates numbers in the given range (inclusively).
<?php
$arr = array();
for ($i = 0; $i < 20; $i ) {
array_push($arr, random_int(1, 10));
}
The source of randomness is quite good (depending on the system).
If you want such random number array generator as a function, do this:
<?php
function random_ints($count, $min, $max) {
$arr = array();
for ($i = 0; $i < $count; $i ) {
array_push($arr, random_int($min, $max));
}
}