Reputation: 4408
I need to get time based unique id which would only consist of numbers, i was thinking to simply use something like this:
str_replace(".", "", microtime(true))
I would use this id for many things, for example comments posting, and i'm expecting quite high traffic so i would like to know how high are the chances of collision with microtime
function?
And perhaps there is a better way to get numerical unique id? Just remember that it has to based on time so sorting could be done.
Upvotes: 3
Views: 27512
Reputation: 351
you can use this to get uniqid but is not numberic:
$id = uniqid(); //58aea16085f6b
use this to convert it to only numbers:
$id = hexdec( uniqid() ); //1560112880181100
if it's too long use this but maybe get negetive numbers:
$id = crc32( uniqid() ); //-1551585806
if you just need posetive numbers you can do it:
$id = abs( crc32( uniqid() ) ); //1551585806
Upvotes: 24
Reputation: 1709
If you need to use a pure time based ID you need to ensure that you avoid collisions so a) use a primary key in the database and then b) use a recursive check to ensure that your time based ID has not already been taken:
$id = getTimeId();
function getTimeId() {
// Generate microtime
// Query to ensure it does not exist
// Return microtime
}
I shall leave it upto you good sir to enjoy making it recursive.
Upvotes: 0
Reputation: 14173
If it must be based on time you could use microtime. But I guess you are storing things in a database so my vote would go for a primary key
column Id
with auto_increment
and then a second column with timestamp
type and a default current time
.
Then you can sort on timestamp and also have a 100% unique identifier even with extremely high traffic. But if ordering is needed (so not searching between dates) then you dont need it based on time.
1, 2, 3, 4 will be in the same order as a microtime key thats just a lot larger and further appart.
UPDATE
If it must be a unique key and cant be used from the database, try the following. The changes of a duplicate key are so slim it can be ignored.
$key = microtime() + floor(rand()*10000);
Upvotes: 5
Reputation: 1722
if you have to avoid collisions time based won't work. eventually you'll get a collision. Why not use a counter with a semaphore.
http://php.net/manual/en/book.sem.php
Upvotes: 0