没有if的字符串echo

时间:2012-02-12 17:29:57

标签: php string random echo

我喜欢50个字符串。

$rand = rand(0,50);

$name[1] = "Jane";
$name[2] = "Marienne";
...
...
...
$name[50] = "Mary";

echo $name[$rand];

如果$ rand ==“2”,我想回复“Marienne”。但上面的代码不起作用。而且我不想使用if语句,因为字符串太多了。你有什么建议我的?感谢。

1 个答案:

答案 0 :(得分:2)

如果您没有像未初始化的$name[0]密钥那样的“DOH”时刻,那么您发布的代码应该可以使用。

但是,如果你想完全避免这个问题,你可以使用array_randdocs函数来挑选一个(伪)随机数组键:

$names = array('Peter', 'Paul', 'John');
echo $names[array_rand($names)];

或者,不要在50中硬编码作为随机范围内的最大值,为什么不尝试:

rand(0, count($names)-1);
相关问题