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.

8
15
1
4
19
7
2
12
5

↓ Articles about PHP ↓
Development in PHP
Arrays in PHP
How to display various PHP timezones
How to insert a variable into a link in PHP
json_decode PHP
How to get screen width with PHP
Calling a function from another file
Premature end of chunk coded message body: closing chunk expected
Find out your HTTP_USER_AGENT
Compare two dates
Classes in PHP 8
Authentication and authorization in PHP 8
↓ Other articles ↓
PHP session locking
Installing PHP frameworks
Installing Yii
Installing Symfony
Installing Laravel
Profiling PHP sites
XDebug - debugging and profiling php code

Article author: Andrei Olegovich