Generate array of random unique numbers in PHP
This will generate an array with 10 random numbers from 0 to 100:
array_map(function () {
return rand(0, 100);
}, array_fill(0, 10, null));
Result:
array(10) {
[0]=>
int(15)
[1]=>
int(97)
[2]=>
int(20)
[3]=>
int(64)
[4]=>
int(57)
[5]=>
int(38)
[6]=>
int(16)
[7]=>
int(53)
[8]=>
int(56)
[9]=>
int(22)
}
Explanation:
array_fill(0, 10, null)
will generate an array with 10 empty itemsarray_map
Applies the callback (first argument) to each item of the array it receives (second argument). In this example, we just return a random number for each array item.
Playground: https://3v4l.org/FffN6
If you need to make sure each generated number is unique:
$uniqueNumbers = 100;
$picked = [];
$uniqueRandomNumbers = array_map(function () use(&$picked, $uniqueNumbers) {
do {
$rand = rand(0, $uniqueNumbers);
} while(in_array($rand, $picked));
$picked[] = $rand;
return $rand;
}, array_fill(0, $uniqueNumbers, null));
https://3v4l.org/mSWBo#v8.0.9
$max = 5;
$done = false;
while(!$done){
$numbers = range(0, $max);
shuffle($numbers);
$done = true;
foreach($numbers as $key => $val){
if($key == $val){
$done = false;
break;
}
}
}
A even shorter solution:
$random_number_array = range(0, 100);
shuffle($random_number_array );
$random_number_array = array_slice($random_number_array ,0,10);
print_r($random_number_array);
Result will be:
[0] => 53
[1] => 6
[2] => 16
[3] => 59
[4] => 8
[5] => 18
[6] => 62
[7] => 39
[8] => 22
[9] => 26