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

↓ 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
Contacts and cooperation:
I recommend our hosting beget.ru
Write to info@urn.su if you:
1. Want to write an article for our site or translate an article into your native language.
2. Want to place thematically relevant ads on the site.
3. Ads on my site pass maximum censorship. If you see an ad block unsuitable for school-age children, shocking or misleading - please contact us by e-mail
4. Found a mistake, inaccuracy, bug, etc. on the site. ... .......
5. Articles can be shared on social media by clicking a network icon: