4

I am generating random numbers using php random function, but I want the generated number should be unique and it should not be repeated again.

----------
php code
 $number = rand(100,100000); //a six digit random number between 100 to 100000 
echo $number;

----------

but I am using this function for multiple times in my code for users so at very rare case there should be a chance of generating same number again. how can i avoid that.

8
  • store number, check if its been used before. only 100% reliable way with random numbers Commented Apr 10, 2018 at 3:37
  • What is this being used for? Commented Apr 10, 2018 at 3:40
  • to make unique id's for customers Commented Apr 10, 2018 at 3:42
  • 1
    areyou storing it in a DB? you could use your primary key too Commented Apr 10, 2018 at 3:44
  • 1
    best way is - 1. make e random number using rand(). 2. grab the current timestamp. 3. add a prefix that could be a string depending on your business logic. 4. combine these three and get a random unique number! This process ensures better accuracy of not getting the same number. Commented Apr 10, 2018 at 3:45

7 Answers 7

2

I would do this:

You said you have branches. The receipt id could look something like this:

$dateString = date('Ymd'); //Generate a datestring.
$branchNumber = 101; //Get the branch number somehow.
$receiptNumber = 1;  //You will query the last receipt in your database 
//and get the last $receiptNumber for that branch and add 1 to it.;

if($receiptNumber < 9999) {

  $receiptNumber = $receiptNumber + 1;

}else{
 $receiptNumber = 1;
} 

Update the receipt database with the receipt number.

$dateString . '-' . $branchNumber . '-' . $receiptNumber;

This will read:

20180406-101-1 

This will be unique(Provided you do less than 10,000 transactions a day.) and will show your employees easily readable information.

Sign up to request clarification or add additional context in comments.

1 Comment

No problem! Cheers
2

If you are storing users in DB you should create column [ID] as primary key with auto increment and that would be best solution.

In other case I'd recommend you to simply store all user id's in ascending order from N to M by reading last ID and adding 1 to it because I see no real gain from random order that only adds complexity to your code.

Comments

1

There are many ways, example:

$freq = [];
$number = rand(100,100000);
$times = 10;
while($times-- > 0)
{
   while(in_array($number, $freq))$number = rand(100,100000);
   $freq[] = $number;
   echo $number . "<br>";
}

This will print 10 random unique numbers.

Comments

1

random_int (PHP 7)

<?php
$number =  random_int(100, 100000);
echo $number;

Comments

1

All you need to do is use timestamp in php as timestamp never cross each other hence it will always generate unique number.You can use time() function in php.

The time() function is used to format the timestamp into a human desired format. The timestamp is the number of seconds between the current time and 1st January, 1970 00:00:00 GMT. It is also known as the UNIX timestamp.

<?php
$t=time();
echo $t;
?>

Also you add a rand() function and insert it in front of the $t to make it more random as if few users work at same time then the timestamp might collide.

<?php
$number = rand(100,100000);
$t=time();
$random = $number.''.$t;

echo $random;
?>

The above will reduce the chance to timestamp collide hence making the probability of number uniqueness almost 100%.

And if you make your column unique in your database then the php wont insert the number hence this bottleneck will ensure you will always get a unique random number.

 bill_id not null unique

12 Comments

It's very possible of getting a concurrency issue if two user/process works at the same time!
yes Erfan you are right about it , therefore another function should be added below to check if the number is equal to the last 10 records if not then insert the number else use a delay function and then insert it .
Erfan ahmed thankyou and adern how can i make delay function
last 10 records is not an ideal threshold of checking uniqueness. Moreover checking each time before insertion is also an overhead and performance heavy. Better using a unique constrain at DB on the generated column, say ran_unq_num not null unique. I've commented on the questions. That should be enough for him to come up with an answer!
can you tell why do you need random number because i will edit the answer with respect to your response .
|
0

If you are using it for something like user id, then you can use uniqid for that. This command gets a prefixed unique identifier based on the current time in microseconds.

Here's how to use it:

string uniqid ([ string $prefix = "" [, bool $more_entropy = FALSE]] )

Where prefix is used if you are generating ids for a lot if hosts at the same time, you can use this to differentiate between various hosts if id is generated at the same microsecond.

more_entropy increases the likeness of getting unique values.

Usage:

<?php
/* A uniqid, like: 4b3403665fea6 */
printf("uniqid(): %s\r\n", uniqid());

/* We can also prefix the uniqid, this the same as 
 * doing:
 *
 * $uniqid = $prefix . uniqid();
 * $uniqid = uniqid($prefix);
 */
printf("uniqid('php_'): %s\r\n", uniqid('php_'));

/* We can also activate the more_entropy parameter, which is 
 * required on some systems, like Cygwin. This makes uniqid()
 * produce a value like: 4b340550242239.64159797
 */
printf("uniqid('', true): %s\r\n", uniqid('', true));
?>

Comments

0

this code must work

some description about code:

  1. generate unique id
  2. extract numbers form unique id with regex
  3. gathering numbers from regex with a loop
<?php

$unique = uniqid("",true);
preg_match_all("!\d+!", $unique ,$matches);
print_r($matches);
$numbers = "";
foreach($matches[0] as $key => $num){
   $numbers .= $num; 
}

echo $numbers;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.