Unique Alphanumeric String in PHP

3 10,565

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.

3 Comments
  1. Michael says

    You’re cool.

  2. Kareem Medhat says

    Thanks for your time because it saved me and my time

  3. Chanty SOK says

    Thank you for saving my day. Nice post.

Leave A Reply

Your email address will not be published.