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));
Example 1: Generate Random Stringsrandom() method is used to generate random characters from the specified characters (A-Z, a-z, 0-9). The for loop is used to loop through the number passed into the generateString() function.
char randomletter = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"[random () % 26]; which would work with any encoding (including EBCDIC, ASCII, UTF-8, ISO-Latin-1) ....
Using random. choice() The random. choice() function is used in the python string to generate the sequence of characters and digits that can repeat the string in any order.
Use this it's easier.
Upper Case
$letter = chr(rand(65,90));
Lowercase
$letter = chr(rand(97,122));
ascii chart
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With