Unique Alphanumeric String in PHP
In this article, we will discuss how to create a unique alphanumeric string in PHP. We are creating a PHP function which creates a unique string contains letter and number (alphanumeric) with the character limit. These kinds of unique string can be used as Voucher Code, Referral Code, Coupon Code, OTP or any kind of Promotional Code.
Here’s the PHP function:
function unique_code($limit) { return substr(base_convert(sha1(uniqid(mt_rand())), 16, 36), 0, $limit); } echo unique_code(8); // Output looks s5s108df 12df54vf
In the above code snippet, I’m using the default PHP functions.
- base_convert – Convert a number between arbitrary bases. You can found more details here.
- sha1 – Calculate the sha1 hash of a string. You can found more details here.
- uniqid – Generate a unique ID. You can found more details here.
- mt_rand – Generate a random value via the Mersenne Twister Random Number Generator. You can found more details here.
Add custom function in Laravel Helper
You can use this in the Laravel Application. You need to add this function to your Helper.php
If you are not familiar with the custom helper in Laravel then you can follow this tutorial.
Hope you like this post, Please feel free to add the comment if any query.
If you like our content, please consider buying us a coffee.
Thank you for your support!
Buy Me a Coffee
You’re cool.
Thanks for your time because it saved me and my time
Thank you for saving my day. Nice post.
made easy and its simple
where $limit comes from? did not set a default value of it?
Sorry this is not unique, substr break this. Even getting 8 chars via mt_rand from 0-9A-Z is more “unique” than this.