2011-12-30 15 views
7

Diciamo che ho avuto tre variabili: -Riprendendo una variabile casuale

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

Come Mi associo a caso uno sulla pagina, come vorrei avere questo modulo nel mio sito web barra laterale che avrebbe cambiato il ogni aggiornamento, a caso?

risposta

16

metterli in un array e scegliere a caso con rand(). I limiti numerici passati a rand() sono zero per il valore inferiore, come il primo elemento nell'array e uno in meno rispetto al numero di elementi nell'array.

$array = array($first, $second, $third); 
echo $array[rand(0, count($array) - 1)]; 

Esempio:

$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 

O molto più semplicemente, chiamando array_rand($array) e passando il risultato di nuovo come una chiave di matrice:

// Choose a random key and write its value from the array 
echo $array[array_rand($array)]; 
+0

Oh grazie :) – Frank

8

usare un array:

$words = array('Hello', 'Evening', 'Goodnight!'); 

echo $words[rand(0, count($words)-1)]; 
+0

ma queste non sono solo andando a essere parole, Sta andando essere molto pesante html. Quindi potrei sostituire 'Primo' con una variabile' $ first' e dichiararla sopra il codice e impostarla come valore? – Frank

+3

Puoi mettere tutto ciò che vuoi in un array. Ma se stai scaricando un html "pesante" in un oggetto visibile, potresti voler riconsiderare il tuo design. –

+0

E con questo intendi cosa? – Frank

3

perché non utilizzare array_rand() per questo:

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

Genera un valore casuale migliore che è possibile utilizzare mt_rand().

Esempio:

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