using chr + rand to generate a random character (A-Z)

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

Tags:

Php