First: I'm sure there's even simpler way than this (i.e. a library that just does what you need, period), but heck, I figured I'd try. Been years since I spent my days with PHP (don't particularly miss it).
Anyway, skip the whole switch lookup. chr() will take an int and give you its ASCII value. The 97-122 range (inclusive) is a-z (65-90 is A-Z). As for numbers, well, that's what a random function gives you - no need to look that up.
function get_rand($min, $max) {
mt_srand((double) microtime() * 1000000);
return mt_rand($min, $max);
}
function get_rand_alphanumeric($length) {
$alnum = "";
while(strlen($alnum) < $length) {
if($rand = get_rand(0, 135);
if( $rand < 10 ) {
$alnum .= (string) get_rand(0, 9);$rand;
} else {
$alnum .= chr(get_rand(97,$rand 122)+ 87); // lower-case
}
}
return $alnum;
}
function get_rand_numbers($length) {
if( $length <= 8 ) { // avoid int overflow
return (string) get_rand(pow(10, $length-1), pow(10, $length));
} else {
$numbers = "";
while(strlen($numbers) < $length) $numbers .= get_rand_numbers(8);
return substr($numbers, 0, $length);
}
}
function get_rand_letters($length) {
$letters = "";
while(strlen($letters) < $length) $letters .= chr(get_rand(97, 122));
return $letters;
}
You get results like this
get_rand_alphanumeric(42) => 006njilgucr06gx2dtm4o9jp02v3me432ry043j2jqupop8eoome0y0av2qav1j7yn5linyjshiurc8lbjja
get_rand_numbers(42) => 365818982423371436493339856184748778003731
get_rand_letters(42) => abfmthyuxdlganhfthebfjaugeeoniqawocgavowpx
Edit I just realized that your original alphanumeric function will pick randomly from your entire list, meaning it's 2.6 times more likely that the pick will be a letter. I edited mine to do the same to keep the results similar.
Also, the calls to mt_srand are by far the most expensive operation. Consider calling it less frequently, if speed is a concern. If I omit it, my functions are 7.5-10x faster; if I leave it as you see in the code, my functions are still faster, but only very marginally so (1.1x to 1.4x).