Put them in an array and randomly select rand()
from it. The numerical boundaries passed to rand()
are zero for the bottom, as the first element in the array, and one less than the number of elements in the array.
$array = array($first, $second, $third); echo $array[rand(0, count($array) - 1)];
Example:
$first = 'first'; $second = 'apple'; $third = 'pear'; $array = array($first, $second, $third); for ($i=0; $i<5; $i++) { echo $array[rand(0, count($array) - 1)] . "\n"; }
Or, simply put, calling array_rand($array)
and passing the result as an array key:
// Choose a random key and write its value from the array echo $array[array_rand($array)];
Michael berkowski
source share