Heim  >  Artikel  >  Backend-Entwicklung  >  php有从固定选项中随机选取的相关函数吗?

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

WBOY
WBOYOriginal
2016-06-06 20:25:091347Durchsuche

随机生成数字可以用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

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn