Echoing out a random variable
Place them into an array and choose from it randomly with rand()
. The numeric bounds passed to rand()
are zero for the lower, 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";
}
// Outputs:
pear
apple
apple
first
apple
Or much more simply, by calling array_rand($array)
and passing the result back as an array key:
// Choose a random key and write its value from the array
echo $array[array_rand($array)];
Use an array:
$words = array('Hello', 'Evening', 'Goodnight!');
echo $words[rand(0, count($words)-1)];
Why not use array_rand()
for this:
$values = array('first', 'apple', 'pear');
echo $values[array_rand($values)];