Home > Backend Development > PHP Tutorial > PHP learning array_rand() array random selection function

PHP learning array_rand() array random selection function

little bottle
Release: 2023-04-06 12:16:01
Original
3228 people have browsed it

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]);
Copy after login

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 ) */ ?>
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template