ItSolutionStuff.com

How to Generate Random Alphanumeric String in PHP?

By Hardik Savani • May 14, 2024
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: PHP
Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

📺 Subscribe on YouTube

We Are Recommending You

How to Check Current PHP Version in Ubuntu?

Read Now →

PHP nl2br() Function Example Tutorial

Read Now →

PHP implode() Function Example Tutorial

Read Now →

PHP Curl Request with P12 Certificate Example

Read Now →

How to Convert XML File to Array in PHP?

Read Now →

PHP MySQL Login with Google Account Example

Read Now →

How to Integrate Google Map using Gmaps JS?

Read Now →

How to Get the File Size in PHP?

Read Now →

How to Check If String is URL or Not in PHP?

Read Now →

MySQL Query to Get Current Month Data Example

Read Now →

How to Find Day Name from Specific Date in PHP?

Read Now →

How to Remove Null Values from Array in PHP?

Read Now →

How to Merge Two Array with Same Keys without Loop in PHP?

Read Now →