Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to generate unique random numbers in php?

Tags:

php

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.

like image 662
nithin singh Gm Avatar asked Oct 27 '25 19:10

nithin singh Gm


1 Answers

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.

like image 116
Joseph_J Avatar answered Oct 30 '25 10:10

Joseph_J