PHP Randoms – Random Functions To Do Random Numbers, Random Strings, Random Files, & More

By  on  

Random values are important to a lot of larger websites. Randoms 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. Here are a few random functions to do random things.

Random Integer

function get_random_number($min = 0, $max = 100) {
	return rand($min,$max);
}

Random String - From Preset Word List (Array)

function get_random_string_from_list($list_of_words) {
	return $list_of_words[rand(0, sizeof($list_of_words)-1)];
}

Random String

function get_random_string($length=6,$characters = "ABCDEFGHIJKLMNOPRQSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_") {
        $num_characters = strlen($characters) - 1;
        while (strlen($return) < $length) {
            $return.= $characters[mt_rand(0, $num_characters)];
        }
        return $return;
}

Random Float

function random_float ($min, $max) {
   return ($min + lcg_value() * (abs($max-$min)));
}

Source: PHP.net

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

Random File From Directory

function get_random_file($dir) {
        while (false !== ($file = readdir($dir))) {
                $files[] = $file;
        }
        return $files[rand(0, sizeof($files)-1)];
}

Recent Features

Incredible Demos

  • By
    MooTools Zoomer Plugin

    I love to look around the MooTools Forge. As someone that creates lots of plugins, I get a lot of joy out of seeing what other developers are creating and possibly even how I could improve them. One great plugin I've found is...

  • By
    Web Audio API

    The Web Audio API allows developers to load and decode audio on demand using JavaScript.  The more I evaluate awesome games for Firefox OS TVs, the more I get to learn about these APIs that I normally wouldn't touch.  The following is a very basic introduction to the WebAudio API...

Discussion

  1. Victor Dotnet

    Wow! Nice tut Bro!

  2. vatsa

    Hi bro, I need help… I am trying to crate a project that would randomly sellect data e.g phone numbers from a database and then send sms to those same numbers with php. Thanks

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!