Home  >  Article  >  Backend Development  >  php有从固定选项中随机选取的相关函数吗?

php有从固定选项中随机选取的相关函数吗?

WBOY
WBOYOriginal
2016-06-06 20:25:091343browse

随机生成数字可以用rand()。但是,我想从几个固定选项中随机选取一个,有这样的函数吗?
比如:选项有北京、上海、广州,从这三个固定选项中随机选取一个。

回复内容:

随机生成数字可以用rand()。但是,我想从几个固定选项中随机选取一个,有这样的函数吗?
比如:选项有北京、上海、广州,从这三个固定选项中随机选取一个。

你的选项应该是个数组吧,用array_rand()可以实现。
array_rand() 函数从数组中随机选出一个或多个元素,并返回。
语法:
array_rand(array,number)
参数描述:
array 必需。规定输入的数组参数。
number 可选。默认是 1。规定返回多少个随机的元素。

w3school的例子:
$a=array("a"=>"Dog","b"=>"Cat","c"=>"Horse");
print_r(array_rand($a,1));
?>
输出:
b

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn