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.

php-banner-strip

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

Related Posts:

About Craig Lotter

Software developer, husband and dad to two little girls. Writer behind An Exploring South African. I don't have time for myself any more.