Home > Backend Development > PHP Tutorial > Display one randomly in the array?

Display one randomly in the array?

WBOY
Release: 2016-10-10 11:56:27
Original
951 people have browsed it

<code> $arry = array('A','B','C','D');
$result = array_rand($arry,2);
foreach ($result as $val) 
{
echo $arry["$val"].""; 
}
</code>
Copy after login
Copy after login

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

Reply content:

<code> $arry = array('A','B','C','D');
$result = array_rand($arry,2);
foreach ($result as $val) 
{
echo $arry["$val"].""; 
}
</code>
Copy after login
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template