php

PHP: Random Data Retrieval

Sometimes we may want to present our data in an unordered fashion, avoiding alphabetical or date based sorting. For example, creating a “Featured” list of articles that changes upon each page load by choosing a handful at random from our database. Another instance may be wanting to change up an image at random for each page or page load. When dealing with the data in our database with the PHP (Hypertext Preprocessor) programming language, we have several options… each of course with it’s pros and cons and thus each being best suited for particular situations. Today we’ll examine two of our options.

Randomize An Array’s Elements

The first option we’ll examine is the shuffle() function. This function effectively shuffles (how’d you guess?) the elements within the array, changing their positioning and sort order. If our array is a simple non-associative collection of elements this the quick and easy way to prepare the contents to be served up at random. Here’s an example:

<?php
    $fruit = array('apples', 'oranges', 'grapes', 'bananas', 'strawberries');
	echo 'Before:<br />';
	print_r($fruit);
 
	echo '<br />';
 
    shuffle($fruit);
    echo 'After:<br />';
	print_r($fruit);
?>

The above code will output something similar to:

Before:
Array ( [0] => apples [1] => oranges [2] => grapes [3] => bananas [4] => strawberries )
After:
Array ( [0] => strawberries [1] => oranges [2] => apples [3] => bananas [4] => grapes )

Of course the “After” array sort order will differ each time. The drawback to the shuffle() function is that it will not preserve key=>value pairs, the keys will effectively be stripped so this may only be desirable in non-associative arrays. More info and several function tweaks that build on shuffle() while preserving key=>value pairs can be found on the PHP shuffle() documentation page.

Return Random Keys From An Array

Another option at our disposal is the array_rand() function. This function will take a given array and return one or more randomly selected keys from within it. The original elements in the array are left untouched, and with the returned key or keys we can then output the associated values from the array. The second parameter in the function tells it how many keys to return, as in the following example:

<?php
    $fruit = array('red'=>'apples', 'orange'=>'oranges', 'purple'=>'grapes', 'yellow'=>'bananas');
	echo '<p>Array Before: '; print_r($fruit); echo '</p>';
 
	$random = array_rand($fruit, 2);
	echo '<p>Two Random Keys: '; print_r($random); echo '<br />';
 
	$valueOne = $random[0];
	$valueTwo = $random[1];
	echo '<p>First Random Value: ' . $fruit[$valueOne] . '<br />';
	echo 'Second Random Value: ' . $fruit[$valueTwo] . '</p>';
 
?>

This code gives us the following possible output:

Array Before: Array ( [red] => apples [orange] => oranges [purple] => grapes [yellow] => bananas )
 
Two Random Keys: Array ( [0] => red [1] => purple ) 
 
First Random Value: apples
Second Random Value: grapes

It’s important to note that if you request only one random key (or don’t specify the second parameter in the function) it will return a single key, otherwise multiple keys are returned as an array. If you request more keys than there are in the original array, the function will return an error. More info can be found on the PHP array_rand() documentation page.

Further Reading on Random Functions

To dive deeper into random functions available in the PHP language, check out the following list of functions in the PHP manual:

Have fun!

Leave a comment

Leave a Reply

Your email address will not be published. Required fields are marked *