Random Functions in PHP
PHP General FunctionsRandom values are very important in many situations. Random values can be used to generate strings for passwords, quotes, and CAPTCHAs. They can also be used for grabbing random numbers for games and other purposes.
1. Random Integer
function get_random_number($min = 0, $max = 100) {
return rand($min,$max);
}
2. Random String - From Word List (Array)
function get_random_string_from_list($list_of_words) {
return $list_of_words[rand(0, sizeof($list_of_words)-1)];
}
3. Random String
function get_random_string($length=6,$characters = "ABCDEFGHIJKLMNOPRQSTUVWXYZ") {
$num_characters = strlen($characters) - 1;
while (strlen($return) < $length) {
$return.= $characters[mt_rand(0, $num_characters)];
}
return $return;
}
4. Random Float
function random_float ($min, $max) {
return ($min + lcg_value() * (abs($max-$min)));
}
5. Random Hex Color
function get_random_hex_color($values = 'abcdef0123456789',$length=6) {
$num_characters = strlen($characters) - 1;
while (strlen($code) < $length) {
$return.= $characters[mt_rand(0, $num_characters)];
}
return '#'.$return;
}
6. Random File From Directory
function get_random_file($dir) {
while (false !== ($file = readdir($dir))) {
$files[] = $file;
}
return $files[rand(0, sizeof($files)-1)];
}