How do you randomly extract the values of n data in an array in PHP?
Best Answer
Array_rand () is useful when you want to remove one or more random cells from an array. It accepts input as an input array and an optional parameter, Num_req, indicating how many units you want to remove-if not specified, the default is 1. If you only take one, Array_rand () returns the key name of a random cell, or returns an array containing the random key name. This allows you to randomly remove the key names and values from the array.
As shown in the following example:
<?php$input = Array ("Neo", "Morpheus", "Trinity", "Cypher", "Tank"), $rand _keys = Array_rand ($input, 2);p rint $input [$ Rand_keys[0]]. "\ n";p rint $input [$rand _keys[1]]. "\ n";
Output:
Trinitycypher
" Attention "
When Num_req is 1 o'clock, returns non-array data , and when Num_req >=2, returns the array data , so if the number of fetching is not determined to be 1, it is recommended to convert the arrays uniformly as follows:
$num _req = max (1, $num _req), $num _req = min ($num _req, Count ($input)), $rand _keys = (array) array_rand ($input, $num _req);
How to randomly extract the value of n data in an array in PHP-Array_rand ()?