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:
1 | $randEM = $input [ array_rand ( $input )]; |
or step by step:
1 2 | $key = array_rand ( $input ); $randEM = $input [ $key ]; |
Method two:
1 2 | shuffle( $input ); $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:
1 | $randEM = array_pop ( array_slice ( $input , rand(0, count ( $input ) - 1), 1)); |
or step by step:
1 2 3 4 | $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)