-4

I want to generate a code randomly with php. The length should be 5 alphanumeric chars.

But I want the first value to be A-Z. How can I do that?

I've done the following, but this seemed too obvious to me... is there another way?

    function randString($length, $charset='ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789')
{
    $str = '';
    $count = strlen($charset);
    while ($length--) {
        $str .= $charset[mt_rand(0, $count-1)];
    }
    return $str;
}   

$code = randString(1,'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
$code .= randString(4);
tshepang
  • 12,111
  • 21
  • 91
  • 136
Vay
  • 117
  • 2
  • 14
  • http://stackoverflow.com/questions/853813/how-to-create-a-random-string-using-php http://stackoverflow.com/questions/4356289/php-random-string-generator http://stackoverflow.com/questions/5438760/generate-random-5-characters-string – qwerty May 07 '13 at 18:39
  • I know how to generate a random alphanumeric string. The issue is that the first value has to be A to Z. – Vay May 07 '13 at 18:41
  • 2
    So what have you tried? – Antony May 07 '13 at 18:43
  • @Vay - Generate a random character from A-Z; then generate a random alphanumeric string with 4 characters in it. – andrewsi May 07 '13 at 18:44

1 Answers1

1

This should be what you're looking for. If you want uppercase letters, just add them to the $chars string.

<?php
$chars = "abcdefghijklmnopqrstuvwxyz";
function generateCode( $chars , $limit = 5 ){
     $charsLength = strlen( $chars );
     $code = $chars[rand(1,$charsLength)-1];
     $chars .= "0123456789";
     $charsLength = strlen( $chars );
     while(strlen($code) < $limit){
         $code .= $chars[rand(1,$charsLength)-1];
     }
}

$myCode = generateCode( $chars );
Filipe Kiss
  • 159
  • 2
  • 11