Definitions and usage
The Array_rand () function returns the random key name in the array, or if you specify that the function returns more than one key name, the array containing the random key name is returned.
Description
The Array_rand () function randomly selects one or more elements from an array and returns.
The second parameter is used to determine how many elements to select. If more than one element is selected, the array containing the random key name is returned, otherwise the key name of the element is returned.
Array_rand () is useful when you want to take one or more random units out of an array. It accepts input as an input array and an optional parameter num_req, indicating how many units you want to take out-if not specified, the default is 1. If you only remove one, Array_rand () returns the key name of a random cell, otherwise it returns an array containing the random key name. This allows you to randomly retrieve 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);
Print $input [$rand _keys[0]]. "\ n";
Print $input [$rand _keys[1]]. "\ n";
Output:
Trinity
Cypher
"Attention"
when Num_req is 1 o'clock, the non-array data is returned, and when Num_req >=2, the array data is returned, so if the number is not determined to be 1, it is recommended that you convert the array in the following way:
$num _req = max (1, $num _req);
$num _req = min ($num _req, Count ($input));
$rand _keys = (array) array_rand ($input, $num _req);
Group randomly sampled shuffle () and Array_rand ()
Random extraction is to break the elements of the original array after the output, which means that each execution, the extraction of the order or elements are different, this feature can be used to display different ads on the page each time using the shuffle () function to implement the random extraction of the array:
<?php
$textArray = Array (' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ', ' 7 ');
Shuffle ($textArray);
Print_r ($textArray);
?>
The results appear as follows:
Array ([0] => 6 [1] => 3 [2] => 7 [3] => 4 [4] => 1 [5] => 2 [6] => 5)
The random ordering of the implemented array elements;
PHP also provides a function that randomly extracts values from an array: Array_rand (), which is called in the following format:
Array_rand (< array >,[the number of elements extracted));
<?php
$arry = Array (' A ', ' B ', ' C ', ' D ');
$result = Array_rand ($arry, 2);
foreach ($result as $val) {
echo $arry ["$val"]. ""; }
?>
The
Results are shown as follows:
B
C
refreshes have different results;