0

I'm trying to make some random string in PHP with 5 letters/numbers. It's working fine but sometimes I get a shorter string.

$characterset='ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
$count=0;
$lenght=strlen($characterset);
$i=5; #number of characters
while($count < $i){
  $num=rand(1,$lenght);
  $letter=substr($characterset, $num, 1);
  $string.=$letter;
  $count++;
}

And strlen($string) is sometimes 4 (checked 100 records, 85 was 4 characters)

3 Answers3

3

String characters, like arrays, start counting from zero. Run your code a bunch of times: in addition to sometimes getting not enough characters, notice how you never get an A in there?

$num = rand(0,$lenght-1); will do it.

As an alternative method, you could do this:

$max_b36 = str_repeat("Z",$number_of_characters);
$max_dec = base_convert($max_b36,36,10);
$rand_dec = rand(0,$max_dec);
$rand_b36 = base_convert($rand_dex,10,36);
$result = sprintf("%0".$number_of_characters."s",$rand_b36);

This method uses (potentially) big numbers though, so it will only support 5 characters (on 32-bit systems) or 12 characters (on 64-bit systems).

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
1

Personally I'd replace your entire logic with this one line wonder :

print $characters = substr(
                          str_shuffle('ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'),
                          0,5)
                          );

(slightly off formatting so it fits on the screeen)

Doug
  • 1,850
  • 23
  • 50
0

Thank you all for help, following code working great:

$characters='ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
$string = '';
$random_string_length = 5;
$max = strlen($characters) - 1;
for ($i = 0; $i < $random_string_length; $i++) {
     $string .= $characters[mt_rand(0, $max)];
}

Is it possible to avoid the same strings? I generated 50 000 records and had 48 the same.