Generate a random string A-Z, a-z, 0-9 in PHP

Find best Web Development tips and Tricks.
Post Reply
arnlweb
Site Admin
Posts: 95
Joined: Wed Jun 22, 2016 1:28 pm
Location: India
Contact:

Generate a random string A-Z, a-z, 0-9 in PHP

Post by arnlweb » Wed Jun 29, 2016 10:37 pm

Random string a to z

Code: Select all

// Start here (a-z)

$length = 1;

$randomletter = substr(str_shuffle("abcdefghijklmnopqrstuvwxyz"), 0, $length);

echo $randomletter;

// End here
Random string 0 to 9

Code: Select all

// Start here (0-9)

$length = 1;

$randomletter = substr(str_shuffle("0123456789"), 0, $length);

echo $randomletter;

// End here
Random string A to Z, a to z and 0 to 9

Code: Select all

// Start here

$length = 1;

$randomletter = substr(str_shuffle("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"), 0, $length);

echo $randomletter;

// End here

You can use a function like this.

Code: Select all

function generaterandomletter($length = 1) {

return substr(str_shuffle("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"), 0, $length);

}

// print the random string.

echo generaterandomletter();

Thanks.

uchedestiny
Posts: 1
Joined: Mon Aug 22, 2016 8:58 am

Re: Generate a random string A-Z, a-z, 0-9 in PHP

Post by uchedestiny » Mon Aug 22, 2016 9:10 am

Thanks! I like this.

But have you checked for duplicate?

Assuming I run it for 50 - 100,000 times, won't there be duplicate?

arnlweb
Site Admin
Posts: 95
Joined: Wed Jun 22, 2016 1:28 pm
Location: India
Contact:

Re: Generate a random string A-Z, a-z, 0-9 in PHP

Post by arnlweb » Wed Oct 04, 2017 8:19 am

No, do not test it. Is there anything I can do to help?

Post Reply