How can I generate a 6 digit unique number? I have verification mechanisms in place to check for duplicate entries.
-
4why not use sequential numbers if thats the case? or use a timestamp? – Dustin Davis Mar 28 '11 at 20:51
-
3Possible duplicate of [php random x digit number](http://stackoverflow.com/questions/8215979/php-random-x-digit-number) – nyedidikeke Feb 16 '17 at 17:56
15 Answers
$six_digit_random_number = random_int(100000, 999999);
As all numbers between 100,000 and 999,999 are six digits, of course.

- 50,943
- 13
- 104
- 142
-
2Do you know howmany random numbers generated from this method? what if get same random number? – saleem ahmed Jan 27 '16 at 15:34
-
1@saleemahmed [That's the problem with randomness, you can never be sure](http://dilbert.com/strip/2001-10-25). No, really, it's quite possible for numbers to repeat and still be random. This is fine. – Charles Jan 27 '16 at 18:50
-
1The other solutions (Tim Cooper and Frosty Z) are better since they also produce numbers between 1 and 100,000. – Samuel Lindblom Aug 10 '17 at 09:51
-
@SamuelLindblom While this is true, those numbers are generated with zeros on the left, which may cause weirdness and side effects, including the possibility of being misinterpreted as octal numbers. By keeping 100000 as the bottom number, you can be sure that it'll always be treated as the intended number. – Charles Aug 19 '17 at 17:36
-
1These types of 6 digit codes are usually used for security purposes. As such it worth noting that in mt_rand docs it advises against using it for these purposes, "Caution This function does not generate cryptographically secure values, and should not be used for cryptographic purposes. If you need a cryptographically secure value, consider using random_int(), random_bytes(), or openssl_random_pseudo_bytes() instead." – Mav2287 May 15 '21 at 23:37
-
Indeedy, we didn't have `random_int` 10 years ago when I created this answer. I've updated it accordingly. – Charles May 18 '21 at 18:17
If you want it to start at 000001
and go to 999999
:
$num_str = sprintf("%06d", mt_rand(1, 999999));
Mind you, it's stored as a string.
-
Is that random (`mt_rand`) or sequential (start at * and go to *)? – Peyman Mohamadpour Dec 29 '16 at 16:15
Another one:
str_pad(mt_rand(0, 999999), 6, '0', STR_PAD_LEFT);
Anyway, for uniqueness, you will have to check that your number hasn't been already used.
You tell that you check for duplicates, but be cautious since when most numbers will be used, the number of "attempts" (and therefore the time taken) for getting a new number will increase, possibly resulting in very long delays & wasting CPU resources.
I would advise, if possible, to keep track of available IDs in an array, then randomly choose an ID among the available ones, by doing something like this (if ID list is kept in memory):
$arrayOfAvailableIDs = array_map(function($nb) {
return str_pad($nb, 6, '0', STR_PAD_LEFT);
}, range(0, 999999));
$nbAvailableIDs = count($arrayOfAvailableIDs);
// pick a random ID
$newID = array_splice($arrayOfAvailableIDs, mt_rand(0, $nbAvailableIDs-1), 1);
$nbAvailableIDs--;
You can do something similar even if the ID list is stored in a database.

- 22,336
- 11
- 85
- 113
There are some great answers, but many use functions that are flagged as not cryptographically secure. If you want a random 6 digit number that is cryptographically secure you can use something like this:
$key = random_int(0, 999999);
$key = str_pad($key, 6, 0, STR_PAD_LEFT);
return $key;
This will also include numbers like 000182 and others that would otherwise be excluded from the other examples.
You can also use a loop to make each digit random and generate random number with as many digits as you may need:
function generateKey($keyLength) {
// Set a blank variable to store the key in
$key = "";
for ($x = 1; $x <= $keyLength; $x++) {
// Set each digit
$key .= random_int(0, 9);
}
return $key;
}
For reference, random_int — Generates cryptographically secure pseudo-random integers that are suitable for use where unbiased results are critical, such as when shuffling a deck of cards for a poker game." - php.net/random_int

- 796
- 2
- 9
- 22
-
I was just looking for ideas / the most effective way to generate 6 digit two-factor authentication codes and this is hands down the best answer here. – caffeinatedbits Mar 27 '21 at 00:21
-
1P.S. I would edit but it says my queue is full. I would suggest the following edits: 1) "$key = str_pad(random_int(0, 999999), 6, "0", STR_PAD_LEFT);" (original answer specifies 9999999 which is seven digits), and 2) add the following reference: "random_int — Generates cryptographically secure pseudo-random integers that are suitable for use where unbiased results are critical, such as when shuffling a deck of cards for a poker game." - https://www.php.net/random_int – caffeinatedbits Mar 27 '21 at 00:26
-
-
@caffeinatedbits good catch on the typo. I made your changes and added a second example. – Mav2287 Sep 04 '21 at 22:41
<?php
$file = 'count.txt';
//get the number from the file
$uniq = file_get_contents($file);
//add +1
$id = $uniq + 1 ;
// add that new value to text file again for next use
file_put_contents($file, $id);
// your unique id ready
echo $id;
?>
i hope this will work fine. i use the same technique in my website.

- 87
- 1
- 3
In PHP 7.0+ I would suggest random_int($min, $max)
over mt_rand()
.
$randomSixDigitInt = \random_int(100000, 999999);
From php.net:
Caution This function does not generate cryptographically secure values, and should not be used for cryptographic purposes. If you need a cryptographically secure value, consider using random_int(), random_bytes(), or openssl_random_pseudo_bytes() instead.
So this depends mostly on context. I'll also add that as of PHP 7.1.0 rand()
is now an alias to mt_rand()
.
Cheers

- 9,514
- 5
- 50
- 69
$characters = '123456789';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < 6; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
$pin=$randomString;

- 965
- 2
- 10
- 28

- 466
- 5
- 5
This will generate random 6 digit number
<?php
mt_rand(100000,999999);
?>

- 4,640
- 3
- 22
- 37

- 3,655
- 3
- 23
- 35
-
2what is the difference between your answer and the one provided by @Charles, at Mar 28, 2011? – Peyman Mohamadpour Dec 29 '16 at 16:17
-
2
<?php echo rand(100000,999999); ?>
you can generate random number

- 1,382
- 1
- 13
- 16
-
5As this question is 6 years old, not sure how much this adds to the answers already posted. – Nigel Ren Oct 14 '17 at 20:42
I would use an algorithm, brute force could be as follows:
First time through loop: Generate a random number between 100,000 through 999,999 and call that x1
Second time through the loop Generate a random number between 100,000 and x1 call this xt2, then generate a random number between x1 and 999,999 call this xt3, then randomly choose x2 or x3, call this x2
Nth time through the loop Generate random number between 100,000 and x1, x1 and x2, and x2 through 999,999 and so forth...
watch out for endpoints, also watch out for x1

- 1,694
- 4
- 21
- 40
This is the easiest method to generate 6 digits random number
$data = random_int(100000, 999999);
echo $data;

- 181
- 2
- 6
You can use $uniq = round(microtime(true));
it generates 10 digit base on time which is never be duplicated

- 1
Among the answers given here before this one, the one by "Yes Barry" is the most appropriate one.
random_int(100000, 999999)
Note that here we use random_int
, which was introduced in PHP 7 and uses a cryptographic random generator, something that is important if you want random codes to be hard to guess. random_bytes
was also introduced in PHP 7 and likewise uses a cryptographic random generator.
Many other solutions for random value generation, including those involving time()
, microtime()
, uniqid()
, rand()
, mt_rand()
, str_shuffle()
, array_rand()
, and shuffle()
, are much more predictable and are unsuitable if the random string will serve as a password, a bearer credential, a nonce, a session identifier, a "verification code" or "confirmation code", or another secret value.
The code above generates a string of 6 decimal digits. If you want to use a bigger character set (such as all upper-case letters, all lower-case letters, and the 10 digits), this is a more involved process, but you have to use random_int
or random_bytes
rather than rand()
, mt_rand()
, str_shuffle()
, etc., if the string will serve as a password, a "confirmation code", or another secret value. See an answer to a related question, and see also: generating a random code in php?
I also list other things to keep in mind when generating unique identifiers, especially random ones.

- 32,158
- 14
- 82
- 96