array_rand

(PHP 4, PHP 5, PHP 7, PHP 8)

array_randPrend une ou plusieurs clés, au hasard dans un tableau

Description

array_rand(array $array, int $num = 1): int|string|array

Sélectionne une ou plusieurs valeurs au hasard dans un tableau et retourne la ou les clés de ces valeurs. Cette fonction utilise un pseudo générateur de nombre aléatoire, ce qui ne convient pas pour de la cryptographie.

Liste de paramètres

array

Le tableau d'entrée.

num

Spécifie le nombre d'entrées que vous voulez récupérer.

Valeurs de retour

Lorsque vous ne récupérez qu'une seule entrée, la fonction array_rand() retourne la clé d'une entrée choisie aléatoirement. Sinon, un tableau de clés d'entrées aléatoires sera retourné. Cela vous permet de faire une sélection au hasard de clés, ou bien de valeurs. Si plusieurs clés sont retournées, alors elles le seront dans l'ordre qu'elles étaient dans le tableau d'origine Le fait de tenter de récupérer plus d'éléments qu'il n'y en a dans le tableau fera qu'une erreur de niveau E_WARNING sera émise, et NULL sera retourné.

Historique

Version Description
7.1.0 L'algorithme interne de génération aléatoire a été modifié pour utiliser le générateur aleatoire de nombre »  Mersenne Twister au lieu de la fonction aléatoire libc

Exemples

Exemple #1 Exemple avec array_rand()

<?php
$input 
= array("Neo""Morpheus""Trinity""Cypher""Tank");
$rand_keys array_rand($input2);
echo 
$input[$rand_keys[0]] . "\n";
echo 
$input[$rand_keys[1]] . "\n";
?>

Voir aussi

  • shuffle() - Mélange les éléments d'un tableau

add a note add a note

User Contributed Notes 34 notes

up
119
Jordan Doyle
10 years ago
Note: array_rand uses the libc generator, which is slower and less-random than Mersenne Twister.

<?php
    $a
= ['http://php.net/', 'http://google.com/', 'http://bbc.co.uk/'];

   
$website = $a[mt_rand(0, count($a) - 1)];
?>

This is a better alternative.
up
52
Anonymous
14 years ago
If the array elements are unique, and are all integers or strings, here is a simple way to pick $n random *values* (not keys) from an array $array:

<?php array_rand(array_flip($array), $n); ?>
up
55
Sebmil
12 years ago
Looks like this function has a strange randomness.

If you take any number of elements in an array which has 40..100 elements, the 31st one is always by far the less occuring (by about 10% less than others).

I tried this piece of code at home (PHP Version 5.3.2-1ubuntu4.9) and on my server (PHP Version 5.2.17), unfortunately i haven't any server with the last version here :

<?php
$valeurs
= range(1, 40);
$proba = array_fill(1, 40, 0);
for (
$i = 0; $i < 10000; ++$i)
{
   
$tirage_tab = array_rand($valeurs, 10);
    foreach(
$tirage_tab as $key => $value)
    {
       
$proba[$valeurs[$value]]++;
    }
}

asort($proba);
echo
"Proba : <br/>\n";
foreach(
$proba as $key => $value)
{
    echo
"$key : $value<br/>\n";
}
?>

In every try, the number of occurrences change a bit but the 31 is always far less (around 2200) than the others (2400-2600). I tried with 50 and 100 elements, no change. I tried with more or less elements to pick (second parameter to array_rand), same result. If you pick only one element it's even worse : 31 has half the result of the others.

For this particular case, i recommend shuffling the array and taking the nth first elements, in this test it's 60% faster and the statistics are ok.
up
22
grzeniufication
6 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( $a, array_flip( array_rand( $a, $n ) ) ) );

// If you want to re-index keys wrap the call in 'array_values':
print_r( array_values( array_intersect_key( $a, array_flip( array_rand( $a, $n ) ) ) ) );
up
27
qeremy
12 years ago
An example for getting random value from arrays;

<?php
function array_random($arr, $num = 1) {
   
shuffle($arr);
   
   
$r = array();
    for (
$i = 0; $i < $num; $i++) {
       
$r[] = $arr[$i];
    }
    return
$num == 1 ? $r[0] : $r;
}

$a = array("apple", "banana", "cherry");
print_r(array_random($a));
print_r(array_random($a, 2));
?>

cherry
Array
(
    [0] => banana
    [1] => apple
)

And example for getting random value from assoc arrays;

<?php
function array_random_assoc($arr, $num = 1) {
   
$keys = array_keys($arr);
   
shuffle($keys);
   
   
$r = array();
    for (
$i = 0; $i < $num; $i++) {
       
$r[$keys[$i]] = $arr[$keys[$i]];
    }
    return
$r;
}

$a = array("a" => "apple", "b" => "banana", "c" => "cherry");
print_r(array_random_assoc($a));
print_r(array_random_assoc($a, 2));
?>

Array
(
    [c] => cherry
)
Array
(
    [a] => apple
    [b] => banana
)
up
14
grzeniufication
6 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, int $n = 1): array
{
    if (
$n < 1 || $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)]);
}
up
12
Wirek
9 years ago
I agree with Sebmil (http://php.net/manual/en/function.array-rand.php#105265) that "array_rand()" produces weird and very uneven random distribution (as of my local PHP 5.3.8 and my public host's PHP 5.2.17).
Unfortunately, I haven't got any access either to a server with the latest PHP version. My info is for those of you who like to check things for themselves and who don't believe all of the official statements in the docs.
I've made a simple adjustment of his test code like this:
<?php
$s
=1;    // Start value
$c=50;    // Count / End value
$test=array_fill($s, $c, 0);
$ts=microtime(true);
for(
$i=0; $i<5000000; $i++){
   
$idx=mt_rand($s, $c);    // Try it with rand() - simpler but more evenly distributed than mt_rand()
   
$test[$idx]++;
}
$te=microtime(true);
$te=($te-$ts)*1000.0;    // Loop time in miliseconds

asort($test);
echo
"Test mt_rand() in ".$te." ms: <br/>\n";
foreach(
$test as $k=>$v) echo "$k :\t$v <br/>\n";
?>

And it appears to me that simple "$idx=rand(0, count($test)-1);" is much better than "$idx=array_rand($test, 1);".
And what's more the simpler and a bit slower (0 ms up to total 712.357 ms at 5 mln cycles) "rand()" is better than "mt_rand()" in simple everyday use cases because it is more evenly distributed (difference least vs. most often numbers: ca. 0.20-1.28 % for "rand()" vs. ca. 1.43-1.68 % for "mt_rand()").
Try it for yourself... although it depends on your software and hardware configuration, range of numbers to choose from (due to random patterns), number of cycles in the loop, and temporary (public) server load as well.
up
12
Anonymous
11 years ago
It doesn't explicitly say it in the documentation, but PHP won't pick the same key twice in one call.
up
4
nospamplease at mail dot com
10 years ago
Random choice with a closure.

$randomChoice  = function($array) {return $array[array_rand($array)];};

$names = ['Dexter', 'Esther', 'David', 'Richard', 'Rachel', 'Belinda'];

echo $randomChoice($names);
up
6
jpinedo
20 years ago
An array of arrays example:

<?php
$banners
[0]['imagen']="imagen0.gif";
$banners[0]['url']="www.nosenada.tal";

$banners[1]['imagen']="imagen1.gif";
$banners[1]['url']="www.nose.tal";

$banners[2]['imagen']="imagen2.gif";
$banners[2]['url']="pagina.html";

$banners[3]['imagen']="imagen3.jpg";
$banners[3]['url']="../pagina.php";

$id_banner = array_rand($banners);

echo 
"Archivo:--".$banners[$id_banner]['imagen']. "<br />\n";
echo 
"URL:-----".$banners[$id_banner]['url']. "<br />\n";
?>
up
3
alexkropivko at(dog) yandex dot ru
18 years ago
There was a mistake at "Paul Hodel (paul at ue dot com dot br) 17-Apr-2003 04:40":
String
echo $new_input = $input[$v];

have to be:
echo $new_input[] = $input[$v];
up
2
Tmy Adeson
9 years ago
<?php
// You can do this, programmatically, using the following code ... Test It Yourself (TIY)

$colors=array(
   
'gray','red','orange','green',
   
'#B2CC80','#CC6699','#B89470','#99CCFF',
);
//colors array

$c1=sizeof($colors)-1;//get position of the last element within the colors array

//    -- OR, if you prefer --
//$c1=count($colors)-1;//get position of the last element within the colors array

//pick a color at random from the colors array - 'Mersenne Twister based'
$color=$colors[mt_rand(0,$c1)];

echo<<<HERE
<!DOCTYPE html>
<html>
<head>
   <meta http-equiv="refresh" content="2">
</head>
<body>
   <div style="width:400px; background-color:
$color; border:1px; text-align:center;" >
    
$color
   </div>
</body>
</html>
HERE;
?>
up
3
Frederick Lemasson aka djassper at gmail
17 years ago
To select a random Value (not a Key) from a Multi-Dimentionnal array I made a recursive function : array_multi_rand()

the following exemple randomly selects an url from a multidimentionnal array :

<?

$Expos
['Google']['Science']='news.google.fr/news?topic=t';
$Expos['Google']['Economie']='news.google.fr/news?topic=b';
$Expos['Google']['Sante']='news.google.fr/news?topic=m';
$Expos['Yahoo']='fr.news.yahoo.com';
$Expos['Events']['LogicielLibre']='agendadulibre.org';
$Expos['MyBlog']='www.kik-it.com';

function
array_multi_rand($Zoo){
   
$Boo=array_rand($Zoo);
    if(
is_array($Zoo[$Boo])){
        return
array_multi_rand($Zoo[$Boo]);
    }else{
        return
$Zoo[$Boo];
    }
}

echo(
array_multi_rand($Expos));

?>
up
3
scandar at home dot se
21 years ago
Note that the int num_req parameter is the required number of element to randomly select. So if your array has 3 element and num_req=4 then array_rand() will not return anything since it is impossible to select 4 random elements out of an array that only contains 3 elements. Many people think that they will get 3 elements returned but that is of course not the case.
up
1
trukin at gmail dot com
18 years ago
Modify of last note:
<?php
if (!function_exists('array_rand')) {
    function
array_rand($array, $lim=1) {
       
mt_srand((double) microtime() * 1000000);
        for(
$a=0; $a<=$lim; $a++){
           
$num[] = mt_srand(0, count($array)-1);
        }
        return @
$num;
    }
}
?>

mt_rand generates a better random number, and with the limit.
up
1
Will-ster
18 years ago
This is something I have been playing with for quite awhile. I'm very new to php, but i finally got it to work. it's a function that will take and array[$arrquo] and find a particular keyword[$find] in the different elements of the array then take those elements that posess that keyword and display them at random

<?php
function popbyword($arrquo,$find)
{
$newarr = array('');
foreach(
$arrquo as $line)
{
  if(
strstr( $line, $find ) )
  {
   
array_push($newarr, $line);

  }
}   
srand((double)microtime()*1000000);
$rquote = array_rand($newarr);
echo
$newarr[$rquote];
}

popbyword($images, 'Albert');
?>

In my case I had this huge array of quotes with 90 some elements. I was able to find certain keywords in those elements then ONLY display the elements that had those keywords. NEAT! Maybe only because I'm new.
up
1
yhoko at yhoko dot com
19 years ago
According to office at at universalmetropolis dot com I have to say that the example is wrong.

<?php
// retrieve one of the options at random from the array
$teamcolours = $teamcolours[rand(0,count($teamcolours))];
?>

The count() function will return the number of items in the array, that's the last index + 1. So if there's 2 items in the array, count() will return 2 but the indices are 0 and 1. Now since rand(x,y) randomizes between x and y inclusively the index from the above example may be out of bounds. Thus you have to subtract 1 from the count:

<?php
   
// Get random item
   
$teamcolours = $teamcolours[rand(0,count($teamcolours)-1)];
?>
up
1
Paul Hodel (paul at ue dot com dot br)
21 years ago
If you trying to get a randon array just use that... it's easier! And you have no repeats...

<?

srand
((float) microtime() * 10000000);

$input = array ("Neo", "Morpheus", "Trinity", "Cypher", "Tank");

$keys = array_rand ($input, sizeof($input));

while (list(
$k, $v) = each($keys))
{
    echo
$new_input = $input[$v];
}

?>
up
1
dragonfly at dragonflyeye dot net
17 years ago
Well, this is interesting.   I don't see anyone else commenting on this, so just in case you were planning to use this function like I was, be prepared: array_rand does not handle multidimensional arrays.  It just ends up returning a list of the X-axis values without the Y-axis arrays.  Bummer.  I'm going to have to find another way to do what I wanted.
up
1
herodesh [-at_] gmail [-dot-] com
16 years ago
this is to generate a random selection from an array with array_rand preety nice, can be used to generate random passwords or anything:

$my_array = array("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "0", "1", "2", "3", "4", "5");
        for ($i=0; $i<=10; $i++)
        {
            $random = array_rand($my_array);
                        //this generates the random number from the array
            $parola .= $my_array[$random];
                        //here we will display the exact charachter from the array
        }
        echo $parola; // printing result
up
2
marco at behnke dot biz
9 years ago
Is there a difference in randomness if you use shuffle instead?

<?php
function array_shuffle($input, $num_of_results) {
   
shuffle($input);
    return
array_chunk($input, $num_of_results, true)[0];
}

$input = array("Neo", "Morpheus", "Trinity", "Cypher", "Tank");
var_dump(array_shuffle($input, 2));

/*
array(2) {
  [0]=>
  string(3) "Neo"
  [1]=>
  string(8) "Morpheus"
}
*/
?>

And yes, I know that my example returns a portion of the array and not just the key numbers
up
0
enanda dot am at gmail dot com
6 years ago
We can use this function to create random HEX Color codes :

<? php

    $color
='#';

   
$colors = array (0,1,2,3,4,5,6,7,8,9,'A','B','C','D','E','F');

    for(
$i=0;$i<6;$i++){

       
$color.=$colors[array_rand($colors)];

    }
       
         echo
$color;

?>

So each time we ran this script it will generate a random HEX color code and print it in the screen .
up
0
notmuqsit at gmail dot com
6 years ago
When the second argument is greater than 1, the output array will be arranged in ascending order.

$a = ["Albert", "James", "Steve", "Charlie", "Sarah"];

The least value of array keys of $a is 0 and the highest is 4 in this case. Now let's do some tests.

//Infinite loops (never ending loops)
while(array_rand($a, 2)[0] !== 4);
while(array_rand($a, 2)[1] !== 0);

//Non-infinite loops.
while(array_rand($a, 2)[0] === 0);
while(array_rand($a, 2)[1] === 4);

Why is this important?
You will never get a perfectly random key if you aren't aware of that.

array_rand($a, 2)[0] will NEVER return the last key (by the last key I mean the last key of the array when you arrange the array keys in ascending order).

array_rand($a, 2)[1] will NEVER return the first key (by the first key I mean the first key of the array when you arrange the array keys in ascending order).

In our case,

$random = array_rand($a, 2);
echo $a[$random[0]];//Possible output: "Albert", "James", "Steve" or "Charlie"
echo $a[$random[1]];//Possible output: "James", "Steve", "Charlie" or "Sarah"

You might want to shuffle($random) in such a case. This is only needed IF you have defined the second parameter and the second parameter > 1.
up
0
sondermann dot m at gmail dot com
7 years ago
It is not written on here but you should note that the keys that are returned are always sorted low to high.
This was unexpected for me since my main reason to use this function was to get a random subset of an array (use case was to list products in a sidebar).

As a result of this, even if the same products were picked randomly another time, they were always arranged in the same way.

This is my solution, may help someone who also needs a fully randomized subset of an array:

<?php
function array_random_keys( $array, $num = 1 ) {
        if ( !
is_array( $array ) ) return $array;
        if( (int)
$num < 1 ) return array();
       
$keys = array_keys($array);
       
shuffle($keys);
        if(
$num == 1 ) {
          return
$keys[0];
        }
        return
array_splice( $keys, 0, $num );
}
?>
up
-1
akalongman at gmail dot com
5 years ago
I'd recommend use random_int() instead of mt_rand()
up
0
BenedictLemieux at gmail dot com
9 years ago
Two things always bugged me with array_rand().

First is its name. It does not sound clear enough whether it gives key or values.

Second and more importantly is its erratic randomness, which is already well documented.

That is why I came up with these two simple functions:

<?php
function random_key($array){
   
$keys=array_keys($array);
    return
$keys[mt_rand(0, count($keys) - 1)];
}   
function
random_value($array){
   
$values=array_values($array);
    return
$values[mt_rand(0, count($values) - 1)];
}
?>

They both work well with any kind of arrays, do not alter the original one like shuffle, are giving more realistic random results, and their names are self describing.

The main drawback is that, as opposed to array_rand, they only gives one element, but at least that is clear from their name. I do believe easy to make random_keys and random_values.
up
1
uvm at sun dot he dot net
22 years ago
If you're just trying to draw a random subset of n elements from an array, it seems more effecient to do something like this:

<?php
function draw_rand_array($array,$draws)
{
       
$lastIndex = count($array) - 1;
       
$returnArr = array();
        while(
$draws > 1)
        {
               
$rndIndex = rand(0,$lastIndex);
               
array_push($returnArr,array_splice($array,$rndIndex,1));
               
$draws--;
               
$lastIndex--;
        }

        return
$returnArr;
}
?>

No messing with indexes when you're done... you just have an array with the elements you're looking for in it.
up
-2
yopai
9 years ago
@Sebmil :
You say this function "has a strange randomness [, because] the 31st one is always by far the less occuring (by about 10% less than others)."

That's right (at least under linux, PHP 5.3). And it's also visible when calling array_rand with 1 as second parameter.

After checking the code, and testing it, I concluded that you have to call srand() at each iteration of your loop.

To be simple, a rand() call is made <n> times when the <n>th key is returned;
I suppose there is a flaw in the pseudorandom number generator (PRNG)  that php uses; somehow the generation has a frequency of 31 (when a random number is sufficiently low, then the 31st after it will be more higher).

Reinitializing the PRNG each time you enter the loop make the problem disappear (and is cheaper, in terms of time, than using shuffle).

In other words, the following code :
for ($i = 0; $i < 10000; ++$i)
{
    /* reinitialize the PRNG --> */ srand();
    $tirage_tab = array_rand($valeurs, 10);
    foreach($tirage_tab as $key => $value)
    {
        $proba[$valeurs[$value]]++;
    }
}

doesn't have the strange behaviour you noticed. No PRNG is perfectly random, so taking the habit of calling srand() from time to time is still a good practice if you rely on a lot of random numbers.
up
0
maxnamara at yahoo dot com
19 years ago
<?php
$input
= array("Neo", "Morpheus", "Trinity", "Cypher", "Tank");

function
my_array_rand($input,$i=2){
srand((float) microtime() * 10000000);

$rand_keys = array_rand($input, $i);

/*
print $input[$rand_keys[0]] . "\n";
print $input[$rand_keys[1]] . "\n";
*/

$res = array();

if(
$i > 1){

for(
$a=0;$a<$i;$a++){

   
$res[] = $input[$rand_keys[$a]];
   
}

}
else{

   
$res[] = $input[$rand_keys];   
   
}

return
$res;
}

$a = my_array_rand($input,3);
echo
"<pre>";
print_r($a);
echo
"</pre>";
?>
up
-1
john at brahy dot com
9 years ago
if you want random elements from an array, this worked pretty well for me.

<?php
//using shuffle randomizes the order of elements

function get_random_elements( $array,$limit = 0 ) {
   
   
shuffle($array);

    if (
$limit > 0 ) {
       
$array = array_splice($array, 0, $limit);
    }
    return
$array;
}
?>
up
-1
info at pavliga dot com
15 years ago
If you want get unique range:

<?php
$n
= 15;

$data = range(1, 20);
$rand = array_rand($data,$n);

for(
$i=0; $i<$n; $i++)
{
echo
$rand[$i]."<br>";
}

?>
up
-2
JS
17 years ago
I wanted to write something that picks a random entry from a 1column-MySQL database - simply Post Of The Moment (potm). I know there surly are many better ways to do it, but I`m rather new to PHP :)  Anyway, it`s simple and no-problem working code.
Of course I assume your DB exists and you always have something in it.

@$link = MySQL_Connect("localhost", "username", "password"); //connect to mysql
mySQL_Select_DB("database"); //..to DB
@$potms = MySQL_Query("SELECT * FROM potm"); //now we get all from our table and store it
MySQL_Close($link); //there`s no need for connection, so we should close it

$potm_array = ''; //sets variables to "zero" values
$i = 0;
while ($entry = MySQL_Fetch_Array($potms)) //now we go through our DB
       {
         $potm_array[$i] = $entry; //our temporary array from which we will random pick a field key
         $i++; //now we increment our field key
       }

$potm_id = array_rand($potw_array); //picks a random key from array
$potm = $potm_array[$potm_id]['name_of_the_field']; //now we have stored our Post Of The Moment in $potm

..hope this helps
up
-1
mickoz[at]parodius[dot]com
21 years ago
For those of you thinking that it does not work for num_req = 1, it is because it return a variable and not an array.  This mainly cause some problem with people using foreach.

The correct way to handle this is explained by that example:

<?php
$some_array
= array("blah","bleh","foo","lele");

$nb_value = 1;

srand ((float) microtime() * 10000000);
$rand_keys = array_rand($some_array, $nb_value);

if(!
is_array($rand_keys))
{
 
$rand_keys = array($rand_keys);
}

print_r($rand_keys); // verify here the array of keys
echo "\n<BR>";
?>

// You can then correctly use the foreach, as it require an array to work
// If you use foreach with one element, it won't work.

<?php
$random_array
= array();

foreach(
$rand_keys as $value)
{
 
array_push($random_array, $some_array[$value]);
}

print_r($random_array);
?>
up
-1
divinity76 at gmail dot com
7 years ago
if you're looking for a cryptographically secure variant (as of speaking, php uses mt_rand), i made this. (limitations: it has no $num parameter. it requires php>=7)

<?php
function csarray_rand(array $arr){
   
$keys=array_keys($arr);
   
$count=count($keys);
    if(
$count===0){
       
//Contrary to documentation, PHP 4 and 5 and 7, up to php 7.1.0alpha3 does not actually return any warning when the array is empty and $num=NULL (and further contradicting the documentation, its NULL by default, not 1, and they are treated differently, 1 gives error, NULL does not.) ... 7.1.0beta1 does throw an error however... follow their example?
       
if(version_compare(PHP_VERSION,'7.1.0beta1','>=')){
           
trigger_error('Warning: csarray_rand(): Array is empty',E_USER_ERROR);
        }
        return
NULL;
    }
   
$csrand=random_int(0,count($keys)-1);
    return
$keys[$csrand];
}
?>
To Top