Hie guys i want to create a random string of numbers where there is a fixed letter B at the beginning and a set of eight integers ending with any random letter, like for example B07224081A where A and the other numbers are random. This string should be unique. How can I do this?
            Asked
            
        
        
            Active
            
        
            Viewed 3,185 times
        
    -1
            
            
        - 
                    3This isn't a cakephp-specific question. Just good old PHP. Very similar: http://stackoverflow.com/questions/853813/how-to-create-a-random-string-using-php – jeremyharris Jul 09 '12 at 15:00
- 
                    Exactly.. Just google up how ti generate random alpha-numeric string and modify the script to your purpose! – Sankha Narayan Guria Jul 09 '12 at 15:03
2 Answers
4
            Do you mean something like this?
$letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
$numbers = rand(10000000, 99999999);
$prefix = "B";
$sufix = $letters[rand(0, 25)];
$string = $prefix . $numbers . $sufix;
echo $string; // printed "B74099731P" in my case
The more characters - the greater chance to generate unique string.
I think that's much better method to use uniqid() since it's based on miliseconds. Uniqueness of generated string is guaranteed.
 
    
    
        Nikola K.
        
- 7,093
- 13
- 31
- 39
- 
                    3In order to actually guarantee uniqueness, you'll need to keep track of the strings you've used and regenerate if you come up with a duplicate. – chaos Jul 09 '12 at 15:17
0
            
            
        This should work for you.
  $randomString = "B";
  for ($i = 0; $i < 9; $i++) {
    if ($i < 8) {
        $randomString.=rand(0,9);
    }  
    if ($i == 8) {
        $randomString.=chr(rand(65,90));
    }
  }
  echo $randomString;
 
    
    
        WhoaItsAFactorial
        
- 3,538
- 4
- 28
- 45
 
    