In PHP, you can use the array_rand() function to randomly take out several values from the array. This function can randomly get one or more elements from the array and return the obtained array name; the syntax format is "array_rand (array,num)", the parameter num specifies the number of array elements to be obtained.
The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
In PHP, you can use the array_rand() function Randomly pick out several values from the array.
array_rand() function can randomly obtain one or more elements from an array and return the obtained array key name. This function uses a pseudo-random number generation algorithm, so it is not suitable for cryptography scenarios. Its syntax format is as follows:
array_rand(array,number)
Parameters | Description |
---|---|
array | Required. Specifies an array. |
number | ## Optional. Specifies how many random elements to return.
Tip: If you omit the number parameter, the function will return a random array key name by default. If the number obtained exceeds the length of the array, it will Will cause an E_WARNING error and return NULL.If only one element needs to be obtained, the array_rand() function will return the obtained key name, otherwise it will return an array containing random key names. After the function runs successfully, the specific value can be obtained based on the randomly obtained array key value. Example: Use the array_rand() function to randomly obtain array elements
<?php $array = array( 'name' => 'php中文网', 'url' => 'http://www.php.cn', 'title' => 'PHP教程', 'article' => 'array_rand()函数' ); echo '<pre class="brush:php;toolbar:false">'; var_dump(array_rand($array)); var_dump(array_rand($array, 2)); var_dump(array_rand($array, 2)); var_dump(array_rand($array, 5)); ?>
PHP Video Tutorial"
The above is the detailed content of How to randomly extract several values from an array in php. For more information, please follow other related articles on the PHP Chinese website!