Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unique ID with time()

If I use:

$t = time();
echo $t;

This will output something like: 1319390934

I have two questions:

  1. This value can be used as unique id ?
  2. how to generate from it a date?

I can't use uniqid(), because I need a value that can be used to order (recent).

like image 790
user947462 Avatar asked Oct 23 '11 17:10

user947462


2 Answers

Using time() as mentioned will give you a sortable way to create unique IDs. Concatenating strings will also further randomize your desired result and still keep it sortable:

$uniqueId= time().'-'.mt_rand();
like image 114
Seralize Avatar answered Oct 04 '22 12:10

Seralize


  1. Obviously this cannot be used as a "unique" id because, well, it's not unique during the duration of the same second.
  2. Look into date.

If you want something that is advertised as a unique id and both can be sorted, you can use something like this that involves uniqid:

$u = time().'-'.uniqid(true);

I 'm perhaps over-simplifying here, taking for granted that all values time is going to produce will have the same number of digits (so that a string sort would produce the same results as a natural sort). If you don't want to make this assumption, then you could consider

$u = sprintf("%010s-%s", time(), uniqid(true));
like image 39
Jon Avatar answered Oct 04 '22 11:10

Jon