|
PHP Random
PHP has two different functions for generating random number, rand() and mt_rand(), which is more random and faster than rand(). This example uses the mt_rand() function.
Random numbers
The example generates a number in the range of 0 to maximum with maximum being the value returned by the mt_getrandmax() function.
<?php
function RandNumber($min, $max) {
if ($min<0 || $min>mt_getrandmax()) {
print "Error: \"Min\" out of range (0-" . mt_getrandmax()-1 . ")<br>\n";
return;
}
if ($max<1 || $max>mt_getrandmax()) {
print "Error: \"Max\" out of range (1-" . mt_getrandmax() . ")<br>\n";
return;
}
if ($max <= $min) {
print "Error: Invalid min/max combination<br>\n";
return;
}
print "Number: " . mt_rand($min,$max) . "<br>\n";
}
?>
Random strings
The example generates a string of random numbers, uppercase letters and lowercase letters depending on the character types included. This is done by getting a random number in three ranges using the ASCII values for the "0-9", "A-Z", and "a-z" characters. These are then combined and added to the result until the requested number of characters has been obtained.
<?php
function RandString($len, $num, $uc, $lc) {
if (!$len || $len<1 || $len>100) {
print "Error: \"Length\" out of range (1-100)<br>\n";
return;
}
if (!$num && !$uc && !$lc) {
print "Error: No character types specified<br>\n";
return;
}
$s="";
$i=0;
do {
switch(mt_rand(1,3)) {
// get number - ASCII characters (0:48 through 9:57)
case 1:
if ($num==1) {
$s .= chr(mt_rand(48,57));
$i++;
}
break;
// get uppercase letter - ASCII characters (a:65 through z:90)
case 2:
if ($uc==1) {
$s .= chr(mt_rand(65,90));
$i++;
}
break;
// get lowercase letter - ASCII characters (A:97 through Z:122)
case 3:
if ($lc==1) {
$s .= chr(mt_rand(97,122));
$i++;
}
break;
}
} while ($i<$len);
print "Character String: $s<br>\n";
}
?>
|