Generate unique random numbers in PHP
Suppose you need three unique numbers from 0 to 9
One number can be generated with
random_int(0,9)
To generate three more unique numbers add each
generated one to an array and keep random_int running until
a number outside the array comes out
<?php
$existing_array = []
while( (in_array( $new_number1 = random_int(0,9)), $existing_array ) );
array_push($existing_array, $new_number);
while( (in_array( $new_number2 = random_int(0,9)), $existing_array ) );
array_push($existing_array, $new_number);
while( (in_array( $new_number3 = random_int(0,9)), $existing_array ) );
array_push($existing_array, $new_number);
This produces three variables $new_number1, $new_number2 , $new_number3, with values from 0 to 9 without repeats.
To generate many random numbers use a for loop
Suppose you need ten random numbers from 0 to 20 without repeats.
<?php
$existing = []
for ($i = 0; $i < 9; $i++) {
while( (in_array( $number = random_int(0,20)), $existing ) );
array_push($existing_array, $new_number);
}
?>
All these numbers are stored in the $existing array
To get them run one more loop
for ($i = 0; $i < 9; $i++) {
echo $existing[$i];
echo '<br>';
You can see such a generator working below - refresh the page (F5 or CTRL + F5) to repeat the generation and confirm there are no repeats.
9
3
1
16
13
7
14
8
12
| PHP session locking | |
| Installing PHP frameworks | |
| Installing Yii | |
| Installing Symfony | |
| Installing Laravel | |
| Profiling PHP sites | |
| XDebug - debugging and profiling php code |