Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate unique 6 digit code

Tags:

string

php

random

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;
    }
like image 569
parcel pik Avatar asked Dec 05 '25 06:12

parcel pik


2 Answers

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.

like image 80
Xorifelse Avatar answered Dec 07 '25 21:12

Xorifelse


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

like image 33
dana Avatar answered Dec 07 '25 19:12

dana