PHP Create a unique order number with a date

I want to generate a unique identifier in the following 12 number formats:

YYYYMMDDXXXX 

Example:

 201403052318 

Where:

YYYYMMDD is the current date value, and another XXXX is a randomly generated value.

 $today = date("Ymd"); $rand = sprintf("%04d", rand(0,9999)); $unique = $today . $rand; 

The unique amount required per day is about 100. What methods should I use to use PHP to prevent possible duplicates in the rand values ​​or to make the entire identifier as unique as possible? Is it possible to use the current time functions to summarize these numbers in the last 4 characters?

Revision: Unique value associated with the MySQL database as the main index of the table. These are initial values ​​that are not associated with any stored information in the database.

+8
date php time format
source share
3 answers

You cannot rely on rand() . You might create a duplicate (Quite rarely for rand(0,9999) to create a duplicate, but it will be at some point).

So instead of going to rand() just create an incremental value (say starting at 1) and add to your generated date.

The next time you restore a new identifier, take this incremental value (say, if you saved it somewhere) should be 1 right?), Increase it and add it to the new date.

Not a perfect solution .. (Critics are welcome)

You can use uniqid in combination with sha-1 and time and do substr() for them for the first 4 characters.

 <?php $today = date("Ymd"); $rand = strtoupper(substr(uniqid(sha1(time())),0,4)); echo $unique = $today . $rand; 

OUTPUT :

 201403094B3F 
+11
source share

I needed to do something similar, a solution that would save time as well as save a unique identifier, and I decided to use the PHP time() function like this

$reference_number = 'BFF-' . time() $reference_number = 'BFF-' . time() ; You can change the BFF to make more sense for your business logic.

My unique link identifier looks like BFF-1393327176 , and the number can be converted from Unix in real time, which will give you, Tue, 25 Feb 2014 11:19:36

I hope this helps

+6
source share

If the unique values ​​generated once, you just need to make a conditional selection for the rand value and store the value in an array, which will be the condition - using inarray -:

 $amount = 100; // the amount of ids $previousValues = array(); for ($i = 0; $i < $amount; $i++){ $rand = rand(0,9999); while (in_array($rand, $previousValues)){ $rand = rand(0, 9999); } $previousValues[] = $rand; $today = date("Ymd"); $unique = $today.$rand; echo $unique."\n"; } 

Checkout this demo .

0
source share

All Articles