CodeBriefly
Tech Magazine

Unique Alphanumeric String in PHP

6 12,652

Get real time updates directly on you device, subscribe now.

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.

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

Get real time updates directly on you device, subscribe now.

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

  4. amar says

    made easy and its simple

  5. Bonachy says

    where $limit comes from? did not set a default value of it?

  6. Kamilos says

    Sorry this is not unique, substr break this. Even getting 8 chars via mt_rand from 0-9A-Z is more “unique” than this.

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. AcceptRead More