I'm using the following to generate a random character from A-Z, but it's occasionally generating the @ symbol. Any idea how to prevent this? Maybe the character range is incorrect?
$letter = chr(64+rand(0,26));
Use this it's easier.
Upper Case
$letter = chr(rand(65,90));
Lowercase
$letter = chr(rand(97,122));
The code below generates a random alpha-numeric string of $length. You can see the numbers there for what 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 an updated version of the function above, it adds the ability to generate a random numeric key OR an alpha numeric key. To generate numeric, simply add the second paramater as true
.
Example Usage
$randomNumber = izrand(32, true); // generates 32 digit number as string
$randomAlphaNumeric = izrand(); // generates 32 digit alpha numeric string
Typecast to Integer
If you want to typecast the number to integer, simply do this after you generate the number. NOTE: This will drop any leading zeros if they exist.
$randomNumber = (int) $randomNumber;
izrand() 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;
}
ASCII code 64 is @
. You want to start at 65, which is A
. Also, PHP's rand
generates a number from min
to max
inclusive: you should set it to 25 so the biggest character you get is 90 (Z
).
$letter = chr(65 + rand(0, 25));
You could use, given you could generate from a-Z:
$range = array_merge(range('A', 'Z'),range('a', 'z'));
$index = array_rand($range, 1);
echo $range[$index];
$range = range('A', 'Z');
$index = array_rand($range);
echo $range[$index];
The below code will generate an alphanumric string of 2 letters and 3 digits.
$string = strtoupper(chr(rand(65, 90)) . chr(rand(65, 90)) . rand(100, 999));
echo $string;