Generate Unique ID in PHP
Generate Unique ID in PHP

PHP – Generate Unique ID in PHP Using hexdec and uniqid Function

PHP – Generate Unique ID Using hexdec() and uniqid() Function

In mane cases, we need to generate unique ID in our application. In today’s article, I will try to show you a unique ID generation by using/combining two built in PHP methods. We will use mainly two methods. One is  hexdec()  and another is uniqid(). These are built in PHP methods. So let’s get started.

Generate unique ID by uniqid() and hexdec():

The uniqid() function generates a unique identifier, based on the current time in microseconds. When uniqid() method passed to the hexdec() function, it converts the hexadecimal value generated by uniqid() into its decimal equivalent.

Let’s see how it works:

  1. uniqid(): Generates a unique identifier based on the current time in microseconds, typically in the format of YYMMDDHHMMSSuuuuuu, where YY is the year, MM is the month, DD is the day, HH is the hour, MM is the minute, SS is the second, and uuuuuu represents microseconds.
  2. hexdec(): Converts a hexadecimal number to its decimal equivalent.

So, hexdec(uniqid()) generates a unique decimal number based on the hexadecimal representation of the current time in microseconds.

Here’s an example of using hexdec(uniqid()) in PHP:

$uniqueDecimal = hexdec(uniqid());
echo $uniqueDecimal;

 

This code will generate a unique decimal number and print it to the screen. The number will be based on the current time in microseconds, converted from hexadecimal to decimal format. Each time we run this code, it will likely produce a different unique decimal number, depending on the current time.

<?php
  $uniqueID = uniqid();
  $uniqueDecimal = hexdec(uniqid());
	
  echo $uniqueID;
  echo '</br>';
  echo $uniqueDecimal;
?>

OUTPUT:


1795650819599684
66122893e2d3f

 

In above code example, the $uniqueID variable is printing the current time in YYMMDDHHMMSSuuuuuu this format which is “1795650819599684”.

After that we are passing  uniqid() function to hexdec() like below.

$uniqueDecimal = hexdec(uniqid());

Which giving us the final hexadecimal value “66122893e2d3f” of “1795650819599684”.

 

Editorial Staff

A Learner and trying to share what I learned!