Repeating an arbitrary variable

Let's say I had three variables: -

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

How would I choose a random page on a page, because I would like to have this module on the sidebar of my site, which will change with each update, by chance ?

+7
source share
4 answers

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"; } // Outputs: pear apple apple first apple 

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)]; 
+17
source

Use an array:

 $words = array('Hello', 'Evening', 'Goodnight!'); echo $words[rand(0, count($words)-1)]; 
+8
source

Why not use array_rand() for this:

 $values = array('first', 'apple', 'pear'); echo $values[array_rand($values)]; 
+4
source

Create the best random value you can use mt_rand () .

Example:

  $first = "Hello"; $second = "Evening"; $third = "Goodnight!"; $array = array($first, $second, $third); echo $array[mt_rand(0, count($array) - 1)]; 
+1
source

All Articles