Post Details

How to Generate Random Alphanumeric String in PHP
25 Nov

How to Generate Random Alphanumeric String in PHP

Hi Guys

In this example, I am going to show you how to generate randomly alphanumeric strings OR numbers in PHP. when you need to generate a random alphanumeric string for your unique field then you can easily create one using substr(), md5(), rand(), unique(), mt_rand(), time(), and str_shuffle() php function you can create several way unique code using following example:

Example

<?php  
   
     $randomString = substr(md5(rand()),0,5);
     var_dump($randomString);
       
     $randomString = rand(10000,99999);
     var_dump($randomString);
       
     $randomString = substr(md5(uniqid(rand(), true)),0,5);
     var_dump($randomString);
       
     $randomString = substr(time(),5);
     var_dump($randomString);
       
     $randomString = substr(str_shuffle(md5(time())),0,5);
     var_dump($randomString);
       
     $randomString = substr( "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" ,mt_rand( 0 ,50 ) ,2 ) .substr( md5( time() ), 1,3);
     var_dump($randomString);
  
?>

 Output:

string(5) "5950d"

int(78616)

string(5) "3d6fa"

string(5) "86806"

string(5) "845fc"

string(5) "WX4ee"

I hope it can help you...

0 Comments

Leave a Comment