比方說,我有三個變量: -呼應出一個隨機變量
$first = "Hello";
$second = "Evening";
$third = "Goodnight!";
我將如何迴應一個隨機到頁面上,因爲我想有這個模塊在我的網站側邊欄會改變每刷新一次,隨機?
比方說,我有三個變量: -呼應出一個隨機變量
$first = "Hello";
$second = "Evening";
$third = "Goodnight!";
我將如何迴應一個隨機到頁面上,因爲我想有這個模塊在我的網站側邊欄會改變每刷新一次,隨機?
將它們放置到一個數組中,並從它與rand()
隨機選擇。傳遞給rand()
的數字邊界對於較低的數字邊界爲零,作爲數組中的第一個元素,並且比數組中元素的數量少一個。
$array = array($first, $second, $third);
echo $array[rand(0, count($array) - 1)];
例子:
$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
或者更簡單地說,通過調用array_rand($array)
並通過將結果返回爲數組鍵:
// Choose a random key and write its value from the array
echo $array[array_rand($array)];
使用數組:
$words = array('Hello', 'Evening', 'Goodnight!');
echo $words[rand(0, count($words)-1)];
爲什麼不使用array_rand()
此:
$values = array('first','apple','pear');
echo $values[array_rand($values)];
生成一個更好的隨機值,您可以使用mt_rand()。
例子:
$first = "Hello";
$second = "Evening";
$third = "Goodnight!";
$array = array($first, $second, $third);
echo $array[mt_rand(0, count($array) - 1)];
哦,謝謝你:) – Frank 2011-12-30 04:36:42