I want to generate 6 digit unique code but i want first 3 are alphabets and last 3 are numbers like below example..
AAA111
ABD156
DFG589
ERF542...
Please help to create code with above combinations..
below is my code..
public function generateRandomString() {
$characters = '1234567890';
$length = 6;
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
You want the first 3 chars as letters and the last 3 chars as number? Then you should handle them both sepperatly.
function genRandStr(){
$a = $b = '';
for($i = 0; $i < 3; $i++){
$a .= chr(mt_rand(65, 90)); // see the ascii table why 65 to 90.
$b .= mt_rand(0, 9);
}
return $a . $b;
}
You can also use function arguments to add dynamicness and for a random order you can do the following:
// PHP >= 7 code
function genRandStr(int $length = 6, string $prefix = '', string $suffix = ''){
for($i = 0; $i < $length; $i++){
$prefix .= random_int(0,1) ? chr(random_int(65, 90)) : random_int(0, 9);
}
return $prefix . $suffix;
}
Use mt_rand() for PHP version < 7, otherwise random_int() is recommended.
You still need to check for possible collisions though and put it in a while loop.
function generateRandomString() {
$letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$digits = '1234567890';
$randomString = '';
for ($i = 0; $i < 3; $i++) {
$randomString .= $letters[rand(0, strlen($letters) - 1)];
}
for ($i = 0; $i < 3; $i++) {
$randomString .= $digits[rand(0, strlen($digits) - 1)];
}
return $randomString;
}
http://sandbox.onlinephpfunctions.com/code/ec0b494c4e08ab220fe7601504c8611459690c33
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With