Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Echoing out a random variable

Let's say I had three variables:-

$first = "Hello";
$second = "Evening";
$third = "Goodnight!";

How would I echo a random one onto the page, as I would like to have this module in my website sidebar that would change on every refresh, randomly?

like image 507
Frank Avatar asked Dec 30 '11 04:12

Frank


1 Answers

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)];
like image 128
Michael Berkowski Avatar answered Oct 05 '22 19:10

Michael Berkowski