Tag Archives: random

PHP: Return Random Element in Array Programming 06 AUG 2014

A quick and easy PHP code snippet to return a random element from a given array:

$items = array('yellow','green','red');
echo $items[array_rand($items)];

All the hard work is being done by the native array_rand php function. Essentially, array_rand picks one or more random entries out of an array, and returns the key (or keys) of the random entries.

Here is an example picking out two random elements from an array:

$input = array("Neo", "Morpheus", "Trinity", "Cypher", "Tank");
$rand_keys = array_rand($input, 2);
echo $input[$rand_keys[0]] . "\n";
echo $input[$rand_keys[1]] . "\n";

Quick and easy.


Related Link: http://php.net/manual/en/function.array-rand.php

How to Generate a Random Number in JavaScript Programming 13 AUG 2013

javascript logoGenerating a random number in JavaScript is a relatively easy thing – we simply made use of JavaScript’s built in random() function, part of the JavaScript Math object.

The random() method returns a random number from 0 (inclusive) up to but not including 1 (exclusive).

If we then combine this method with the floor() method (also from the JavaScript Math object – Give x, returns x, rounded downwards to the nearest integer), then it becomes trivial to quickly generate a random number.

For example:

//Return a random number between 1 and 10:

//Return a random number between 1 and 50:

Simple and effective.

PHP: How to Generate a Random String Containing Both Letters and Numbers Programming 11 MAY 2012

To generate a string containing a random selection of both letters and numbers (i.e. an alphanumeric string) using PHP is pretty trivial.

Essentially what we want to do is define a string containing all the characters we wish to use in the generated string. Then randomly select characters from the string and glue them all together until we get a random string of the desired length.

Coded as a function, you get:

function rand_string( $length = 5 ) {
	$str = ''; //the resulting random string
	$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";	 //characters making up the random string

	$size = strlen( $chars );
	for( $i = 0; $i < $length; $i++ ) {
		$str .= $chars[ rand( 0, $size - 1 ) ];

	return $str;

Pretty simple, but quite useful actually.

How to create a Variable Length String of Random Characters using JavaScript Programming 04 MAY 2012

Generating random strings is always necessary when working with things like voucher or password generation, and so today’s quick JavaScript function looks at returning a specified length of string containing a a selection of randomly selected characters and numbers.

The function works by specifying a string containing all the characters you wish to be used in your randomly generated string. Using the random() function and mixing it up a little to generate essentially a character position, we can grab a character off the previously mentioned character string. Rinse and repeat for the desired length of string, adding everything together to at last come up with your string of random characters.

function randomString(string_length) {
	var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZ";
	var randomstring = '';
	for (var i=0; i<string_length; i++) {
		var rnum = Math.floor(Math.random() * chars.length);
		randomstring += chars.substring(rnum,rnum+1);
	return randomstring;

Nice and random, just like this image.


A Simple Random Prize Winner Draw PHP Script Programming 23 APR 2012

If you are working with a small to medium data set and want to draw a random selection of prize winners from your collected data, this small PHP prize draw snippet works pretty well and is nice and should be pretty simple to adapt to your needs.

The idea here is to run a SQL statement to give you a list of all the unique customers in the identified data set, build two arrays, the first a keyed array with the customer’s details for printing purposes and a second containing their unique identifier ID key. The second array will be checked to ensure that only unique keys are contained, then shuffled using PHP’s built in shuffle function, before finally slicing off the desired amount of winners (remembering to pad this number ever so slightly so that we can generate both a winners list as well as a backup list for when winners can’t be contacted).

So very simple, but as you will find, pretty damn effective.

In this sample code, my database contains surveyors in a surveyors table and survey data in a surveys table.

$detailed = array(); //full surveyor account details, i.e. name and telephone
$fulllist = array(); //resulting list containing the unique keys retrieved by the SQL statement
$winners = array(); //final winners array
$backup = array(); //backup winners array

$winnerslength = 10; //the number of winners we desire
$backuplength = round(($winnerslength / 2), 0, PHP_ROUND_HALF_UP); //number of backup winners, in this case 5

//example SQL to give us a list of surveyors. Normally you would at this point add your filter requirements, like date range, data filters, etc in the WHERE clause.
$tempwinners = mysql_query("SELECT DISTINCT sa.`id`, sa.`name`,sa.`telephone` FROM `surveys` AS s LEFT JOIN `surveyor-accounts` AS sa ON s.`surveyor-id` = sa.`id`);

//populate both the keyed array containing all the surveyor details, as well as our workhorse array which contains only the surveyor IDs
    while ($tempwinner = mysql_fetch_assoc($tempwinners)) {
        $detailed[$tempwinner['id']] = $tempwinner;
        $fulllist[] = $tempwinner['id'];

//one last check to make sure we are unique

//shuffle the winners

//if the winners pool is smaller or equal to the desired winners count, use everything
    if (count($fulllist) <= $winnerslength) {
        foreach ($detailed as $detailedrow) {
            $winners[] = $detailedrow;
    } else {
//slice off our winners and backup winners from the shuffled list
        $temps = array_slice($fulllist, 0, ($winnerslength + $backuplength));
        $runner = 0;
//populate the arrays
        foreach ($temps as $detailedrow) {
            if ($runner < $winnerslength) {
                $winners[] = $detailed[$detailedrow];
                $runner = $runner + 1;
            } else {
                $backup[] = $detailed[$detailedrow];

//and voila, you now have a randomly drawn winners and backup winners array!
echo '<pre>';
echo '<p>Winners List</p>';
echo '<p>Backup Winners</p>';
echo '</pre>';

And that’s that. Simple, but effective.

PHP: How to Scramble an Array CodeUnit 16 NOV 2011

PHP comes packaged with an awesome little function that makes scrambling an array, i.e. randomly rearranging its contents, a doddle. Aptly named shuffle, the shuffle() function randomizes the order of elements in an array.

As an input array, you simply need to pass it the array to be shuffled, with the function returning either true or false depending on the outcome. The array is passed in by reference, meaning that the original array is shuffled. Note also that existing keys are removed and new keys are assigned, making it useless for associative arrays where the key/value pairs are actually important.

Nevertheless, still a pretty useful function in my opinion. To use:

$numbers = array(1,2,3,4,5);


PHP: Random Color Generator Function CodeUnit 20 OCT 2010

Although I’ve posted simple random color generating code snippets before, I’ve noticed since that most of them have a flaw in that they sometimes don’t always produce a proper six character long hex color code.

Hence I have posted my latest random color generating PHP function to these pages in the interest of reminding myself at a later stage when I need it again!

So let’s have a look at the function shall we?

function generateRandomColor(){
    $randomcolor = '#' . strtoupper(dechex(rand(0,10000000)));
    if (strlen($randomcolor) != 7){
        $randomcolor = str_pad($randomcolor, 10, '0', STR_PAD_RIGHT);
        $randomcolor = substr($randomcolor,0,7);
return $randomcolor;

Pretty simple really.

Grab a random decimal number, convert it to hex and pad right with some zeroes to ensure the proper character length.

Fairly random and guaranteed to always give you pretty results!