6

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).

Jared Farrish
  • 48,585
  • 17
  • 95
  • 104
user947462
  • 929
  • 6
  • 18
  • 28

4 Answers4

15

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();
Seralize
  • 1,117
  • 11
  • 27
  • 2
    Yes make sure you at mt_rand, other wise two or more users could have the same unique id if they come at exactly the same time. – Mike Oct 23 '11 at 18:44
4
  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));
Community
  • 1
  • 1
Jon
  • 428,835
  • 81
  • 738
  • 806
  • Since it's for a database, an `auto_increment` column paired with a `NOW()` column could also work, depending on the use. – Jared Farrish Oct 23 '11 at 17:46
1

If you are using this code in an environment where you have a user account with a unique ID, you can append time() to their account ID to generate a unique ID.

You can turn time() back into a date string using:

$time = time();
echo 'The datestamp for (' . $time . ') is ' . date("Y-m-d", $time);

Of course the date format can be altered using any of PHP's date() format.

Patrick Moore
  • 13,251
  • 5
  • 38
  • 63
0

I would probably do this:

$id = microtime();
Jens Törnell
  • 23,180
  • 45
  • 124
  • 206