In lot of applications, we need to pick up one element randomly from an array. For example, we need to select a random color for some text from a group of predefined colors. Below is several methods one can use to carry out this task.

Method one: using the PHP function array_rand()

One-line code:

$randEM = $input[array_rand($input)];

or step by step:

$key = array_rand($input);
$randEM = $input[$key];

Method two:

$randEM = $input[0];

The return value of shuffle function is a Boolean: TRUE on success or FALSE on failure. The two-line codes shown above cannot be combined into one.

Method three:
One-line code:

$randEM = array_pop(array_slice($input, rand(0, count($input) - 1), 1));

or step by step:

$input_length = count($input);
$offset = rand(0, $input_length- 1);
$oneEmArr = array_slice($input, $offset, 1);
$randEM = array_pop($oneEmArr);
Several ways to fetch a random element from an array (PHP)

Leave a Reply

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