How to Generate Random Alphanumeric String in PHP?

By Hardik Savani May 14, 2024 Category : PHP

In this example i am going to show you how to generate randomly alphanumeric string OR number in PHP. when you need you generate random alphanumeric string for your unique field then you can easily create using substr(), md5(), rand(), uniqid(), 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...

Tags :
Shares