Mic*_*ski 17
将它们放入一个数组中并随机选择rand().传递给的数字边界rand()对于较低的数字为零,作为数组中的第一个元素,并且小于数组中元素的数量.
$array = array($first, $second, $third);
echo $array[rand(0, count($array) - 1)];
Run Code Online (Sandbox Code Playgroud)
例:
$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
Run Code Online (Sandbox Code Playgroud)
或者更简单地说,通过调用array_rand($array)并将结果作为数组键传回:
// Choose a random key and write its value from the array
echo $array[array_rand($array)];
Run Code Online (Sandbox Code Playgroud)
使用数组:
$words = array('Hello', 'Evening', 'Goodnight!');
echo $words[rand(0, count($words)-1)];
Run Code Online (Sandbox Code Playgroud)
为什么不用array_rand()于此目的:
$values = array('first', 'apple', 'pear');
echo $values[array_rand($values)];
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11792 次 |
| 最近记录: |