<code> $arry = array('A','B','C','D'); $result = array_rand($arry,2); foreach ($result as $val) { echo $arry["$val"].""; } </code>
Excuse me, this will randomly generate 2 sets of ABCD combinations, such as BC DC AB, etc.
But what I want to display is to display only one. Randomly display A or B or C or D from the array.
How to do this?
After I changed 2 to 1, it failed
<code> $arry = array('A','B','C','D'); $result = array_rand($arry,2); foreach ($result as $val) { echo $arry["$val"].""; } </code>
Excuse me, this will randomly generate 2 sets of ABCD combinations, such as BC DC AB, etc.
But what I want to display is to display only one. Randomly display A or B or C or D from the array.
How to do this?
After I changed 2 to 1, it failed
<code> mixed array_rand ( array $array [, int $num = 1 ] ) # Picks one or more random entries out of an array, and returns the key (or keys) of the random entries. It uses a pseudo random number generator that is not suitable for cryptographic purposes. </code>
will randomly return the keys in the specified array. Depending on the requirements, $num
will return one key or multiple keys in the form of array
.
If you have an array
<code><?php $arry = array('A','B','C','D'); </code>
Now if you want to randomly output one element in the array each time, you can get it in the following way:
<code><?php $arry = array('A','B','C','D'); $rand_key = array_rand($array, 1); echo $array[$rand_key]; </code>
In the same way, you can implement other random element keys and obtain random elements of the array.
<code class="php">$array = array('A','B','C','D'); $newArray = $array; shuffle($newArray); echo $newArray[0]; </code>
Picks one or more random entries out of an array, and returns the key
(or keys) of the random entries. It uses a pseudo random number
generator that is not suitable for cryptographic purposes.
If the second parameter is 1 or absent, what is returned is not an array, but just a number
<code class="php"> $result = array_rand($arry,2); // 是一个**数组** 如[1,2,3] $result = array_rand($arry,1); // 只是一个**数字** 如 1, 并不是[1] </code>