0

I am creating a ticket system for learning purposes, and I was wondering how would I create a simple unique ticket ID that would be similiar to this: gD8f-jxS

It would have 4 characters of random case in the first part

(letters and numbers are allowed, then it would have a dash, and again 3 random letters or numbers of any case.

Satish Sharma
  • 9,547
  • 6
  • 29
  • 51
WittyPleb
  • 553
  • 2
  • 10
  • 22
  • 6
    Are you married to that pattern? Because it's quite a lot easier to just use `uniqid()`. – Michael Berkowski May 20 '12 at 22:44
  • Somewhat, but if that is much easier, I can use it, is there any way to shorten it? If not it's okay. – WittyPleb May 20 '12 at 22:47
  • No it cannot be shortened unless you did string manips on it, which would break its uniqueness. Search this site for using PHP to generate Youtube ids. There have been many examples for making short identifiers. – Michael Berkowski May 20 '12 at 22:49

1 Answers1

5
public function generateCode(){

    $unique =   FALSE;
    $length =   7;
    $chrDb  =   array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','0','1','2','3','4','5','6','7','8','9');

    while (!$unique){

          $str = '';
          for ($count = 0; $count < $length; $count++){

              $chr = $chrDb[rand(0,count($chrDb)-1)];

              if (rand(0,1) == 0){
                 $chr = strtolower($chr);
              }
              if (3 == $count){
                 $str .= '-';
              }
              $str .= $chr;
          }

          /* check if unique */
          //$existingCode = UNIQUE CHECK GOES HERE  
          if (!$existingCode){
             $unique = TRUE;
          }
    }
    return $str;
}
J A
  • 1,776
  • 1
  • 12
  • 13