不带 if 的字符串回显
我有大约50根弦。
$rand = rand(0,50);
$name[1] = "Jane";
$name[2] = "Marienne";
...
...
...
$name[50] = "Mary";
echo $name[$rand];
例如,如果 $rand=="2" 我想回显“Marienne”。但上面的代码不起作用。而且我不想使用 if 语句,因为字符串太多。你有什么建议我?谢谢。
I have like 50 strings.
$rand = rand(0,50);
$name[1] = "Jane";
$name[2] = "Marienne";
...
...
...
$name[50] = "Mary";
echo $name[$rand];
I want to echo "Marienne" if $rand=="2" for example. But the code above is not working. And I don't want to use if statement because there are too many strings. What do you suggest me ? Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您没有像未初始化的
$name[0]
键这样的“DOH”时刻,您发布的代码应该可以工作。但是,如果您想完全避免该问题,您可以使用
array_rand< /code>docs
函数来挑选(伪)随机数组密钥:
或者,代替硬编码为
50
作为随机范围内的最大值,为什么不尝试:Your posted code should work if you don't have "DOH" moments like an uninitialized
$name[0]
key.However, if you want to avoid that problem altogether you could use the
array_rand
docs function to pick out a (pseudo) random array key:Alternatively, instead of hard-coding in
50
as your max in the random range, why not try: