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)

5
  • anyway, why it is only sometimes not correct? 99% records were good Commented Jul 5, 2017 at 13:13
  • 1
    Because substr silently returns false, if you try to get a character from a position beyond the string end ... Commented Jul 5, 2017 at 13:15
  • Try this. Commented Jul 5, 2017 at 13:16
  • stackoverflow.com/questions/5438760/… Commented Jul 5, 2017 at 13:16
  • You might like to fix the Notice: Undefined variable: string by declaring $string = '';' just outside the loop. .= operators only work properly on pre initialised variables Commented Jul 5, 2017 at 13:18

3 Answers 3

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).

Sign up to request clarification or add additional context in comments.

Comments

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)

1 Comment

Worth noting that this will generate strings with no duplicate characters. Pretty cool, though!
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.