In this tutorial, we will show you how you can easily generate 6,8,10,12 digit random, unique, alphanumeric string and number in PHP.
Generate 6,8,10,12 digit random, unique, alphanumeric string and Numbers in PHP
- Method 1:- Using str_shuffle() Function
- Method 2:- Using md5() Function
- Method 3:- To generate random, unique, alphanumeric numbers in PHP
- 6-digit alphanumeric number
- 8-digit alphanumeric number
Method 1:- Using str_shuffle() Function
The PHP str_shuffle() function is a built-in function in PHP, which is used to randomly shuffle all the characters of the string passed to the function as a parameter.
Ex 1:- php generates alphanumeric random string
<?php $length = 10; $str = '1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcefghijklmnopqrstuvwxyz'; echo substr(str_shuffle($str), 0, $length); ?>
The result of the above code is:
G8ckJ1x3VE
Method 2:- Using md5() Function
The md5() function is used to calculate the MD5 hash of a string, pass the timestamp as an argument and the md5 function will convert them to 32 bit characters.
<?php echo substr(md5(microtime()), 0, 10); echo "<br>"; echo substr(md5(microtime()), 0, 8); ?>
Result of the above code is:
5fa44a2bbc b1c7c213
Method 3:- To generate random, unique, alphanumeric numbers in PHP
6-digit alphanumeric number:
Using the below-given function, you can generate 6 digits random unique alphanumeric numbers in PHP:
function generateRandomString($length = 6) { $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; $result = ''; for ($i = 0; $i < $length; $i++) { $result .= $characters[rand(0, strlen($characters) - 1)]; } return $result; } // Usage example: echo generateRandomString();
8-digit alphanumeric number:
Using the below given function, you can generate 8 digits random unique alphanumeric numbers in PHP:
function generateRandomString($length = 8) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$result = '';
for ($i = 0; $i < $length; $i++) {
$result .= $characters[rand(0, strlen($characters) - 1)];
}
return $result;
}
// Usage example:
echo generateRandomString();