array_rand

(PHP 4, PHP 5)

array_randВыбирает одно или несколько случайных значений из массива

Описание

mixed array_rand ( array $input [, int $num_req = 1 ] )

Выбирает одно или несколько случайных значений из массива. Возвращает ключ (или ключи) данных случайных элементов.

Список параметров

input

Входной массив.

num_req

Определяет количество выбираемых элементов. Попытка выбрать больше элементов, чем есть в массиве, сгенерирует ошибку уровня E_WARNING.

Возвращаемые значения

Если вы выбираете только одно значение, функция array_rand() возвращает ключ, соответствующий этому значению. В обратном случае, она возвращает массив ключей, соответствующих случайным значениям. Это сделано так образом, чтобы дать возможность выбрать из массива как случайные значения, так и случайные ключи.

Список изменений

Версия Описание
5.2.10 Возвращаемый массив ключей больше не возвращается в случайном порядке.
4.2.0Генератор случайных чисел инициализируется автоматически.

Примеры

Пример #1 Пример использования 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";
?>

Смотрите также

  • shuffle() - Перемешивает массив

Коментарии

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.
2001-07-09 21:09:37
http://php5.kiev.ua/manual/ru/function.array-rand.html
I modified fake_array_rand to always only return 1 element, and did some benchmarks against calling array_rand with the second parameter as 1.  I ran 100 samples for each function for each number of elements and took the average result.  While the internal array_rand is faster for a small number of elements, it scales very poorly.

1 elements: 2.0619630813599E-05 sec. for array_rand,8.4352493286133E-05 sec. for fake_array_rand
10 elements: 2.1675825119019E-05 sec. for array_rand,8.427619934082E-05 sec. for fake_array_rand
100 elements: 2.9319524765015E-05 sec. for array_rand,8.4599256515503E-05 sec. for fake_array_rand
1000 elements: 0.0001157283782959 sec. for array_rand,8.5572004318237E-05 sec. for fake_array_rand
10000 elements: 0.0016669762134552 sec. for array_rand,8.5201263427734E-05 sec. for fake_array_rand
100000 elements: 0.015599734783173 sec. for array_rand,8.5580348968506E-05 sec. for fake_array_rand
1000000 elements: 0.18011983394623 sec. for array_rand,8.6690187454224E-05 sec. for fake_array_rand

<?php
function fake_array_rand ($array

       
$count count ($array); 
       
# Help keep the number generator random :) 
       
$randval and usleep ("0.$randval"); 

       
# Seed the random number generator 
        # Generate a random number 
       
srand ((double) microtime() * 10000000); 
       
$randval rand(); 

       
# Use the random value to 'pick' an entry from the array 
        # Count the number of times that the entry is picked
       
++$index[$randval $count];

        return 
$array[$randval $count];
}
?>
2002-06-14 18:20:58
http://php5.kiev.ua/manual/ru/function.array-rand.html
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);
?>
2002-12-01 22:28:23
http://php5.kiev.ua/manual/ru/function.array-rand.html
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.
2003-04-13 12:58:16
http://php5.kiev.ua/manual/ru/function.array-rand.html
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 ($inputsizeof($input));

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

?>
2003-04-17 16:40:10
http://php5.kiev.ua/manual/ru/function.array-rand.html
It is correct that using array_rand() with num_req=1 will return an integer and not an array, but why get so complicated with getting just the one value.  The K.I.S.S. method would suggest to do it this way:

<?
srand
((double)microtime() * 10000000);
$originalArray = array("red""blue""green""brown"
"cyan""magenta""purle""cheezy");
$pickOne array_rand($originalArray1);
$aRandomSelection $originalArray[$pickOne ];
echo 
"$aRandomSelection was the random selection made";
?>

You only need to use the foreach if the num_req >=2. In those cases the array_rand() function will return an array of random elements which are a subset of the original array.  When num_req = 1, the array_rand() function returns an integer that signifies a randomly picked key of the original array.  Hope this clarifies things ... it works for me.
2003-06-24 02:06:42
http://php5.kiev.ua/manual/ru/function.array-rand.html
Автор:
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";
?>
2003-11-02 03:15:39
http://php5.kiev.ua/manual/ru/function.array-rand.html
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)]; 
?>
2004-08-27 21:16:25
http://php5.kiev.ua/manual/ru/function.array-rand.html
<?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>";
?>
2005-03-13 05:22:33
http://php5.kiev.ua/manual/ru/function.array-rand.html
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];
2005-06-16 09:21:00
http://php5.kiev.ua/manual/ru/function.array-rand.html
As wazaawazaa600 at msn dot com pointed out, a multi-dimensional array doesn't work with this function. So, I hope I can help someone with this :)

<?php
/**
 * Returns a number of random elements from an array.
 *
 * It returns the number (specified in $limit) of elements from
 * $array. The elements are returned in a random order, exactly
 * as it was passed to the function. (So, it's safe for multi-
 * dimensional arrays, aswell as array's where you need to keep
 * the keys)
 *
 * @author Brendan Caffrey  <bjcffnet at gmail dot com>
 * @param  array  $array  The array to return the elements from
 * @param  int    $limit  The number of elements to return from
 *                            the array
 * @return array  The randomized array
 */
function array_rand_keys($array$limit 1) {
   
$count = @count($array)-1;

   
// Sanity checks
   
if ($limit == || !is_array($array) || $limit $count) return array();
    if (
$count == 1) return $array;

   
// Loop through and get the random numbers
   
for ($x 0$x $limit$x++) {
       
$rand rand(0$count);

       
// Can't have double randoms, right?
       
while (isset($rands[$rand])) $rand rand(0$count);

       
$rands[$rand] = $rand;
    }

   
$return = array();
   
$curr current($rands);

   
// I think it's better to return the elements in a random
    // order, which is why I'm not just using a foreach loop to
    // loop through the random numbers
   
while (count($return) != $limit) {
       
$cur 0;

        foreach (
$array as $key => $val) {
            if (
$cur == $curr) {
               
$return[$key] = $val;

               
// Next...
               
$curr next($rands);
                continue 
2;
            } else {
               
$cur++;
            }
        }
    }

    return 
$return;
}
?>
2005-08-29 19:29:58
http://php5.kiev.ua/manual/ru/function.array-rand.html
Автор:
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.
2006-01-01 18:18:16
http://php5.kiev.ua/manual/ru/function.array-rand.html
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(0count($array)-1);
        }
        return @
$num;
    }
}
?>

mt_rand generates a better random number, and with the limit.
2006-03-16 15:23:21
http://php5.kiev.ua/manual/ru/function.array-rand.html
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.
2006-07-07 10:57:02
http://php5.kiev.ua/manual/ru/function.array-rand.html
Автор:
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
2006-09-04 06:07:50
http://php5.kiev.ua/manual/ru/function.array-rand.html
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));

?>
2006-12-04 02:57:35
http://php5.kiev.ua/manual/ru/function.array-rand.html
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
2007-09-05 06:36:52
http://php5.kiev.ua/manual/ru/function.array-rand.html
<?php
// a foreach friendly version of array_rand
function Select_Random_Indices($source_array$count 1)
{
    if(
$count 0)
    {
        if(
$count == 1)
        {
           
$result = array(array_rand($source_array$count));
        }
        else
        {
           
$result array_rand($source_array$count);
        }
    }
    else
    {
       
$result = array();
    }

    return 
$result;
}

// using the above function to pick random values instead of entries
function Select_Random_Entries($source_array$count 1)
{
   
$result = array();
   
$index_array Select_Random_Indices($source_array$count);

    foreach(
$index_array as $index)
    {
       
$result[$index] = $source_array[$index];
    }

    return 
$result;
}
?>
2008-12-15 10:11:20
http://php5.kiev.ua/manual/ru/function.array-rand.html
If you want get unique range:

<?php
$n 
15;

$data range(120);
$rand array_rand($data,$n);

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

?>
2008-12-28 15:52:08
http://php5.kiev.ua/manual/ru/function.array-rand.html
Автор:
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); ?>
2009-10-02 04:04:38
http://php5.kiev.ua/manual/ru/function.array-rand.html
Автор:
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(140);
$proba array_fill(1400);
for (
$i 0$i 10000; ++$i)
{
   
$tirage_tab array_rand($valeurs10);
    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.
2011-08-05 15:18:24
http://php5.kiev.ua/manual/ru/function.array-rand.html
Автор:
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 == $r[0] : $r;
}

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

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($a2));
?>

Array
(
    [c] => cherry
)
Array
(
    [a] => apple
    [b] => banana
)
2012-03-07 15:18:34
http://php5.kiev.ua/manual/ru/function.array-rand.html
Автор:
It doesn't explicitly say it in the documentation, but PHP won't pick the same key twice in one call.
2012-07-13 17:42:13
http://php5.kiev.ua/manual/ru/function.array-rand.html
Автор:
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(0count($a) - 1)];
?>

This is a better alternative.
2013-05-19 12:49:26
http://php5.kiev.ua/manual/ru/function.array-rand.html
Random choice with a closure.

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

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

echo $randomChoice($names);
2013-08-13 17:18:29
http://php5.kiev.ua/manual/ru/function.array-rand.html
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 ) {
   
   
shuffle($array);

    if ( 
$limit ) {
       
$array array_splice($array0$limit);
    }
    return 
$array;
}
?>
2014-05-08 02:00:40
http://php5.kiev.ua/manual/ru/function.array-rand.html
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_resultstrue)[0];
}

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

/*
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
2014-09-12 04:52:22
http://php5.kiev.ua/manual/ru/function.array-rand.html
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(0count($keys) - 1)];
}   
function 
random_value($array){
   
$values=array_values($array);
    return 
$values[mt_rand(0count($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.
2014-09-14 06:31:08
http://php5.kiev.ua/manual/ru/function.array-rand.html
Автор:
@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.
2015-01-08 03:21:40
http://php5.kiev.ua/manual/ru/function.array-rand.html
Автор:
<?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;
?>
2015-01-08 16:29:53
http://php5.kiev.ua/manual/ru/function.array-rand.html
/*
useful function to sort an array randomly
*/
function sort_array_rand($array) {
    $result = array();
    $y = sizeof($array);
    $x = 0;           
    while ($x < pow($y, 2)) {
        $result[] = $array[array_rand($array)];
        $x++;
    }
    return array_unique($result);
}
2015-02-13 18:17:11
http://php5.kiev.ua/manual/ru/function.array-rand.html
Автор:
I agree with Sebmil (function.array-rand#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$c0);
$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.
2015-04-16 14:43:17
http://php5.kiev.ua/manual/ru/function.array-rand.html
Verified 2015-06-03 -- this function produces VERY uneven "random" distribution.
2015-06-04 12:13:21
http://php5.kiev.ua/manual/ru/function.array-rand.html
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];
}
?>
2016-10-15 16:59:19
http://php5.kiev.ua/manual/ru/function.array-rand.html
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 ) {
        if ( !
is_array$array ) ) return $array;
        if( (int)
$num ) return array();
       
$keys array_keys($array);
       
shuffle($keys);
        if( 
$num == ) {
          return 
$keys[0];
        }
        return 
array_splice$keys0$num );
}
?>
2016-11-17 17:41:05
http://php5.kiev.ua/manual/ru/function.array-rand.html

    Поддержать сайт на родительском проекте КГБ