简体   繁体   中英

How to generate unique 6 digit code

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

please check below code:

<?php
    $string1 = str_shuffle('abcdefghijklmnopqrstuvwxyz');
    $random1 = substr($string1,0,3);
    $string2 = str_shuffle('1234567890');
    $random2 = substr($string2,0,3);

    echo $random = $random1.$random2;
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM