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
    CSS Counters

    Counters.  They were a staple of the Geocities / early web scene that many of us "older" developers grew up with;  a feature then, the butt of web jokes now.  CSS has implemented its own type of counter, one more sane and straight-forward than the ole...

  • By
    Send Email Notifications for Broken Images Using MooTools AJAX

    One of the little known JavaScript events is the image onError event. This event is triggered when an image 404's out because it doesn't exist. Broken images can make your website look unprofessional and it's important to fix broken images as soon as possible.

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!