Skip to content

uniqid()

In this article, we will focus on the PHP uniqid() function. We will provide you with an overview of the function, how it works, and examples of its use.

Introduction to the uniqid() function

The uniqid() function is a built-in function in PHP that is used to generate a unique ID based on the current time in microseconds. It is a powerful tool that can be used to generate unique identifiers for various purposes, such as generating session IDs or tracking unique visitors to a website.

The uniqid() function takes two optional arguments: a prefix to prepend to the generated ID, and a boolean value indicating whether to generate a more unique ID.

How to use the uniqid() function

Using the uniqid() function is very simple. You just need to call the function and it will generate a unique ID based on the current time in microseconds. Here is an example:

How to use the uniqid() function?

php
<?php
$id = uniqid();
echo "Generated ID: " . $id . "\n";
?>

In this example, we call the uniqid() function and assign the returned ID to a variable $id. We then output the generated ID to the console using echo statements.

You can also specify a prefix to prepend to the generated ID, like this:

Example of PHP uniqid()

php
<?php
$id = uniqid('example_');
echo "Generated ID: " . $id . "\n";
?>

In this example, we call the uniqid() function with a prefix of example_, which is prepended to the generated ID.

Advanced usage

The uniqid() function can also be used in more advanced scenarios. For example, if you want to generate a more unique ID, you can pass a boolean value of true as the second argument, like this:

Example of using PHP uniqid() function

php
<?php
$id = uniqid('', true);
echo "Generated ID: " . $id . "\n";
?>

In this example, we call the uniqid() function with an empty prefix and a boolean value of true, which generates a more unique ID.

Conclusion

In conclusion, the uniqid() function is a powerful tool for generating unique IDs based on the current time in microseconds. By understanding how to use the function and its advanced usage scenarios, you can take advantage of this feature to generate unique identifiers for various purposes in your PHP scripts.

Practice

What is the function of uniqid() in PHP?

Do you find this helpful?

Dual-run preview — compare with live Symfony routes.