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