Home >Backend Development >PHP Tutorial >PHP learning array_rand() array random selection function
This article mainly talks about PHP's array_rand() array random value function, and attaches the code, which has certain reference value. Interested friends can learn it.
array_rand() function
The array_rand() function is to randomly remove one or more elements from the array.
mixed array_rand(array $input [,int $num_req]);
array_rand() function accepts an input parameter and an optional parameter num_req. The input parameter is used to specify the accepted array, and num_req is used to specify the number of elements to be taken out. The default is 1. If only one element is taken out, array_rand() will return the key of a random element, otherwise it will return an array containing random keys.
The code is as follows:
<?php $input=array("科比","姚明","詹姆斯","艾佛森","基德"); echo "<pre class="brush:php;toolbar:false">"; echo "随机获取一个元素" . "<br/>"; print_r(array_rand($input)); echo "<br/>"; echo "随机获取两个元素" . "<br/>" ; print_r(array_rand($input,2)); echo ""; /*运行结果: 随机获取一个元素 2 随机获取两个元素 Array ( [0] => 2 [1] => 3 ) */ ?>
The article ends here, I hope it will be helpful to you.
Related tutorials: PHP video tutorial
The above is the detailed content of PHP learning array_rand() array random selection function. For more information, please follow other related articles on the PHP Chinese website!