PHP: Hypertext Preprocessor (original) (raw)
array_rand
(PHP 4, PHP 5, PHP 7, PHP 8)
array_rand — Pick one or more random keys out of an array
Description
Caution
This function does not generate cryptographically secure values, and must not be used for cryptographic purposes, or purposes that require returned values to be unguessable.
If cryptographically secure randomness is required, the Random\Randomizer may be used with the Random\Engine\Secure engine. For simple use cases, the random_int() and random_bytes() functions provide a convenient and secure API that is backed by the operating system’s CSPRNG.
Parameters
array
The input array. Cannot be empty.
num
Specifies how many entries should be picked. Must be greater than zero, and less than or equal to the length of array
Return Values
When picking only one entry, array_rand() returns the key for a random entry. Otherwise, an array of keys for the random entries is returned. This is done so that random keys can be picked from the array as well as random values. If multiple keys are returned, they will be returned in the order they were present in the original array.
Errors/Exceptions
Throws a ValueError if array
is empty, or if num
is out of range.
Changelog
Version | Description |
---|---|
8.0.0 | array_rand() now throws a ValueError if num is out of range; previously an**E_WARNING** was raised, and the function returned null. |
8.0.0 | array_rand() now throws a ValueError if array is empty; previously an**E_WARNING** was raised, and the function returned null. |
7.1.0 | The internal randomization algorithm has been changed to use the » Mersenne Twister Random Number Generator instead of the libc rand function. |
Examples
Example #1 array_rand() example
<?php $input = array("Neo", "Morpheus", "Trinity", "Cypher", "Tank"); <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>r</mi><mi>a</mi><mi>n</mi><msub><mi>d</mi><mi>k</mi></msub><mi>e</mi><mi>y</mi><mi>s</mi><mo>=</mo><mi>a</mi><mi>r</mi><mi>r</mi><mi>a</mi><msub><mi>y</mi><mi>r</mi></msub><mi>a</mi><mi>n</mi><mi>d</mi><mo stretchy="false">(</mo></mrow><annotation encoding="application/x-tex">rand_keys = array_rand(</annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.8889em;vertical-align:-0.1944em;"></span><span class="mord mathnormal" style="margin-right:0.02778em;">r</span><span class="mord mathnormal">an</span><span class="mord"><span class="mord mathnormal">d</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.3361em;"><span style="top:-2.55em;margin-left:0em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mathnormal mtight" style="margin-right:0.03148em;">k</span></span></span></span><span class="vlist-s"></span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span><span class="mord mathnormal">eys</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">=</span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mord mathnormal">a</span><span class="mord mathnormal" style="margin-right:0.02778em;">rr</span><span class="mord mathnormal">a</span><span class="mord"><span class="mord mathnormal" style="margin-right:0.03588em;">y</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.1514em;"><span style="top:-2.55em;margin-left:-0.0359em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mathnormal mtight" style="margin-right:0.02778em;">r</span></span></span></span><span class="vlist-s"></span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span><span class="mord mathnormal">an</span><span class="mord mathnormal">d</span><span class="mopen">(</span></span></span></span>input, 2); echo <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>i</mi><mi>n</mi><mi>p</mi><mi>u</mi><mi>t</mi><mo stretchy="false">[</mo></mrow><annotation encoding="application/x-tex">input[</annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mord mathnormal">in</span><span class="mord mathnormal">p</span><span class="mord mathnormal">u</span><span class="mord mathnormal">t</span><span class="mopen">[</span></span></span></span>rand_keys[0]] . "\n"; echo <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>i</mi><mi>n</mi><mi>p</mi><mi>u</mi><mi>t</mi><mo stretchy="false">[</mo></mrow><annotation encoding="application/x-tex">input[</annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mord mathnormal">in</span><span class="mord mathnormal">p</span><span class="mord mathnormal">u</span><span class="mord mathnormal">t</span><span class="mopen">[</span></span></span></span>rand_keys[1]] . "\n"; ?>
See Also
- Random\Randomizer::pickArrayKeys() - Select random array keys
- Random\Randomizer::shuffleArray() - Get a permutation of an array
Found A Problem?
15 years ago
`If the array elements are unique, and are all integers or strings, here is a simple way to pick nrandom∗values∗(notkeys)fromanarrayn random values (not keys) from an array nrandom∗values∗(notkeys)fromanarrayarray:
`
12 years ago
It doesn't explicitly say it in the documentation, but PHP won't pick the same key twice in one call.
7 years ago
`<?php/**
- Wraps array_rand call with additional checks
- TLDR; not so radom as you'd wish.
- NOTICE: the closer you get to the input arrays length, for the n parameter, the output gets less random.
- e.g.: array_random($a, count($a)) == $a will yield true
- This, most certainly, has to do with the method used for making the array random (see other comments).
- @throws OutOfBoundsException – if n less than one or exceeds size of input array
- @param array $array – array to randomize
- @param int $n – how many elements to return
- @return array
*/
function array_random(array array,intarray, int array,intn = 1): array
{
if ($n < 1 || n>count(n > count(n>count(array)) {
throw new OutOfBoundsException();
}
return (
$n !== 1)
? array_values(array_intersect_key($array, array_flip(array_rand($array, $n))))
: array($array[array_rand($array)]);
}`
7 years ago
<?php // An example how to fetch multiple values from array_rand $a = [ 'a', 'b', 'c', 'd', 'e', 'f', 'g' ]; $n = 3;// If you want to fetch multiple values you can try this: print_r( array_intersect_key( <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>a</mi><mo separator="true">,</mo><mi>a</mi><mi>r</mi><mi>r</mi><mi>a</mi><msub><mi>y</mi><mi>f</mi></msub><mi>l</mi><mi>i</mi><mi>p</mi><mo stretchy="false">(</mo><mi>a</mi><mi>r</mi><mi>r</mi><mi>a</mi><msub><mi>y</mi><mi>r</mi></msub><mi>a</mi><mi>n</mi><mi>d</mi><mo stretchy="false">(</mo></mrow><annotation encoding="application/x-tex">a, array_flip( array_rand( </annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:1.0361em;vertical-align:-0.2861em;"></span><span class="mord mathnormal">a</span><span class="mpunct">,</span><span class="mspace" style="margin-right:0.1667em;"></span><span class="mord mathnormal">a</span><span class="mord mathnormal" style="margin-right:0.02778em;">rr</span><span class="mord mathnormal">a</span><span class="mord"><span class="mord mathnormal" style="margin-right:0.03588em;">y</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.3361em;"><span style="top:-2.55em;margin-left:-0.0359em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mathnormal mtight" style="margin-right:0.10764em;">f</span></span></span></span><span class="vlist-s"></span></span><span class="vlist-r"><span class="vlist" style="height:0.2861em;"><span></span></span></span></span></span></span><span class="mord mathnormal" style="margin-right:0.01968em;">l</span><span class="mord mathnormal">i</span><span class="mord mathnormal">p</span><span class="mopen">(</span><span class="mord mathnormal">a</span><span class="mord mathnormal" style="margin-right:0.02778em;">rr</span><span class="mord mathnormal">a</span><span class="mord"><span class="mord mathnormal" style="margin-right:0.03588em;">y</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.1514em;"><span style="top:-2.55em;margin-left:-0.0359em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mathnormal mtight" style="margin-right:0.02778em;">r</span></span></span></span><span class="vlist-s"></span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span><span class="mord mathnormal">an</span><span class="mord mathnormal">d</span><span class="mopen">(</span></span></span></span>a, $n ) ) ) );// If you want to re-index keys wrap the call in 'array_values': print_r( array_values( array_intersect_key( <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>a</mi><mo separator="true">,</mo><mi>a</mi><mi>r</mi><mi>r</mi><mi>a</mi><msub><mi>y</mi><mi>f</mi></msub><mi>l</mi><mi>i</mi><mi>p</mi><mo stretchy="false">(</mo><mi>a</mi><mi>r</mi><mi>r</mi><mi>a</mi><msub><mi>y</mi><mi>r</mi></msub><mi>a</mi><mi>n</mi><mi>d</mi><mo stretchy="false">(</mo></mrow><annotation encoding="application/x-tex">a, array_flip( array_rand( </annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:1.0361em;vertical-align:-0.2861em;"></span><span class="mord mathnormal">a</span><span class="mpunct">,</span><span class="mspace" style="margin-right:0.1667em;"></span><span class="mord mathnormal">a</span><span class="mord mathnormal" style="margin-right:0.02778em;">rr</span><span class="mord mathnormal">a</span><span class="mord"><span class="mord mathnormal" style="margin-right:0.03588em;">y</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.3361em;"><span style="top:-2.55em;margin-left:-0.0359em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mathnormal mtight" style="margin-right:0.10764em;">f</span></span></span></span><span class="vlist-s"></span></span><span class="vlist-r"><span class="vlist" style="height:0.2861em;"><span></span></span></span></span></span></span><span class="mord mathnormal" style="margin-right:0.01968em;">l</span><span class="mord mathnormal">i</span><span class="mord mathnormal">p</span><span class="mopen">(</span><span class="mord mathnormal">a</span><span class="mord mathnormal" style="margin-right:0.02778em;">rr</span><span class="mord mathnormal">a</span><span class="mord"><span class="mord mathnormal" style="margin-right:0.03588em;">y</span><span class="msupsub"><span class="vlist-t vlist-t2"><span class="vlist-r"><span class="vlist" style="height:0.1514em;"><span style="top:-2.55em;margin-left:-0.0359em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mathnormal mtight" style="margin-right:0.02778em;">r</span></span></span></span><span class="vlist-s"></span></span><span class="vlist-r"><span class="vlist" style="height:0.15em;"><span></span></span></span></span></span></span><span class="mord mathnormal">an</span><span class="mord mathnormal">d</span><span class="mopen">(</span></span></span></span>a, $n ) ) ) ) );
3 years ago
`array_rand () takes a random value without ever being able to go back in its choice of random value.
A simple example:
I decide to mix an array of 10 entries to retrieve 3 values. This choice will give increasing and random values.
$myarray = range(1,10);
pm=arrayrand(pm = array_rand(pm=arrayrand(myarray,3);
// $pm return array(0->0,1->6,2->8)
But if I decide to shuffle an array of 10 entries to get 10 entries, array_rand () will choose to assign a value to each return value and therefore the return array will not be random.
gm=arrayrand(gm = array_rand(gm=arrayrand(myarray,count($myarray));
// $gm not random array(0->0,1->1,2->2,3->3,4->4,5->5,6->6,7->7,8->8,9->9)
The easiest way to have a truly random value:
either use array_rand () in a loop of 1 value at a time
$deg = range(-60,60);
$size = range(16,64);
$color = ["blue","red","green","pink","orange","purple","grey","darkgreen","darkkhaki"];
$i = 0;
$longueur = 10;
do{
++$i;
printf("%s",
deg[arrayrand(deg[array_rand(deg[arrayrand(deg)],
size[arrayrand(size[array_rand(size[arrayrand(size)],
color[arrayrand(color[array_rand(color[arrayrand(color)],
alnum[arrayrand(alnum[array_rand(alnum[arrayrand(alnum)]);
}while($i < $longueur);
or simply use shuffle () to shuffle the array really randomly.
`
divinity76+spam at gmail dot com ¶
3 years ago
`for a cryptographically secure version, try
max=count(max = count ( max=count(array ) - 1; if ($max < 0) { throw new ValueError ( 'Argument #1 ($array) cannot be empty' ); } return key ( array_slice ( array,randomint(0,array, random_int ( 0, array,randomint(0,max ), 1, true ) ); }$tests = [ [5, 6, 7], ['a' => 1, 'b' => 2, 'c' => 3], ['zero', 4 => 'four', 9 => 'nine'], ["PEAN"=>0], [] ]; foreach ($tests as $test) { echo array_rand_cryptographically_secure($test) . "\n"; }?>(this is an improved version, which unlike the first version, avoids copying all the keys)
`