Using chr + rand to generate a random character (AZ)

I use the following to generate a random character from AZ, but it sometimes generates an @ character. Any idea how to prevent this? Maybe the character range is wrong?

$letter = chr(64+rand(0,26)); 
+9
source share
5 answers

It’s easier to use.

Uppercase

 $letter = chr(rand(65,90)); 

Lowercase

 $letter = chr(rand(97,122)); 

ASCII chart

The code below generates a random alphanumeric string of length $. You can see the numbers there that you need.

 function izrand($length = 32) { $random_string=""; while(strlen($random_string)<$length && $length > 0) { $randnum = mt_rand(0,61); $random_string .= ($randnum < 10) ? chr($randnum+48) : ($randnum < 36 ? chr($randnum+55) : $randnum+61); } return $random_string; } 

update: 12.19.2015

Here is the updated version of the function above, it adds the ability to generate a random digital key OR an alphanumeric key. To generate a number, just add the second parameter as true .

Usage example

$randomNumber = izrand(32, true);//generates 32 digit number as string $randomNumber = izrand(32, true);//generates 32 digit number as string $randomAlphaNumeric = izrand();//generates 32 digit alpha numeric string $randomAlphaNumeric = izrand();//generates 32 digit alpha numeric string

Type cast to Integer

If you want to enter a number into an integer, just do it after generating the number. NOTE. This will remove any leading zeros if they exist.

$randomNumber = (int) $randomNumber;

Isrand () v2

 function izrand($length = 32, $numeric = false) { $random_string = ""; while(strlen($random_string)<$length && $length > 0) { if($numeric === false) { $randnum = mt_rand(0,61); $random_string .= ($randnum < 10) ? chr($randnum+48) : ($randnum < 36 ? chr($randnum+55) : chr($randnum+61)); } else { $randnum = mt_rand(0,9); $random_string .= chr($randnum+48); } } return $random_string; } 
+22
source

ASCII code 64 is @ . You want to start at 65, i.e. A In addition, PHP rand generates a number from min to max inclusive: you must set it to 25, so the largest character you get is 90 ( Z ).

 $letter = chr(65 + rand(0, 25)); 
+3
source

You can use if you can generate from aZ:

 $range = array_merge(range('A', 'Z'),range('a', 'z')); $index = array_rand($range, 1); echo $range[$index]; 
+1
source
 $range = range('A', 'Z'); $index = array_rand($range); echo $range[$index]; 
0
source

The code below will generate an alphanumeric string of 2 letters and 3 digits.

 $string = strtoupper(chr(rand(65, 90)) . chr(rand(65, 90)) . rand(100, 999)); echo $string; 
-1
source

All Articles