Golden Apple Web & Design

Freelance Web Development, Graphic Design & Layouts, Wordpress Specialization

Home 9 PHP 9 PHP: Random Data Retrieval

PHP: Random Data Retrieval

by | PHP, Wordpress | 0 comments

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:

[codesyntax lang=”php”]

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

	echo '<br />';

    shuffle($fruit);
    echo 'After:<br />';
	print_r($fruit);
?>

[/codesyntax]

The above code will output something similar to:

[codesyntax lang=”text”]

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

[/codesyntax]

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:

[codesyntax lang=”php”]

<?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>';

?>

[/codesyntax]

This code gives us the following possible output:

[codesyntax lang=”text”]

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

[/codesyntax]

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!

0 Comments

Submit a Comment

Your email address will not be published.