|
|
 |
array_rand (PHP 4, PHP 5) array_rand --
Pick one or more random entries out of an array
Descriptionmixed array_rand ( array input [, int num_req] )
array_rand() is rather useful when you want to
pick one or more random entries out of an array. It takes an
input array and an optional argument
num_req which specifies how many entries you
want to pick - if not specified, it defaults to 1.
If you are picking only one entry, array_rand()
returns the key for a random entry. Otherwise, it returns an array
of keys for the random entries. This is done so that you can pick
random keys as well as values out of the array.
Note: As of PHP 4.2.0, there is no need
to seed the random number generator with srand() or
mt_srand() as this is now done automatically.
Example 1. array_rand() example |
<?php
srand((float) microtime() * 10000000);
$input = array("Neo", "Morpheus", "Trinity", "Cypher", "Tank");
$rand_keys = array_rand($input, 2);
echo $input[$rand_keys[0]] . "\n";
echo $input[$rand_keys[1]] . "\n";
?>
|
|
See also shuffle().
User Contributed Notes
array_rand
maxnamara at yahoo dot com
13-Mar-2005 05:22
<?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);
$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>";
?>
yhoko at yhoko dot com
27-Aug-2004 08:16
According to office at at universalmetropolis dot com I have to say that the example is wrong.
<?php
$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
$teamcolours = $teamcolours[rand(0,count($teamcolours)-1)];
?>
leighm at linuxbandwagon dot com leigh morresi
08-Mar-2004 09:36
Another array based password generator, this one is a port from the python mailman version.
this generates slightly predictable but human readable passwords that people can remember
output passwords are for example "rikanumi"
<?php
function MakeRandomPassword($length=6) {
$_vowels = array ('a', 'e', 'i', 'o', 'u');
$_consonants = array ('b', 'c', 'd', 'f', 'g', 'h', 'k', 'm', 'n','p', 'r', 's', 't', 'v', 'w', 'x', 'z');
$_syllables = array ();
foreach ($_vowels as $v) {
foreach ($_consonants as $c) {
array_push($_syllables,"$c$v");
array_push($_syllables,"$v$c");
}
}
for ( $i=0;$i<=($length/2);$i++) $newpass=$newpass.$_syllables[array_rand($_syllables) ];
return $newpass;
?>
}
tim dot meader at gsfc dot nasa dot gov
05-Mar-2004 08:31
Just thought I would contribute a password generation function
that uses array_rand. I wrote this because I
could not find anywhere a PHP equivalent of the ability
that the String::Random module in Perl has, which allows
you to specify a schema for how you want the random
string created. In other words: I want 2 Uppercase, 3
lowercase, 2 intergers...etc. This isn't too comprehensive,
notably it doesn't account for one choosing more itterations
of a particular type than there are in the array (ie -
choosing more than 10 numbers from output). Additionally,
this doesn't allow for any repeated characters. Hope it can
be of use... comments appreciated.
<?php
function &doGeneratePasswords()
{
$l_achLowercase = array("a","b","c","d","e","f","g","h",
"i","j","k","m","n","o","p","q",
"r","s","t","u","v","w","x",
"y","z");
$l_iNumLowercase = count($l_achLowercase);
$l_achUppercase = array("A","B","C","D","E","F","G","H",
"J","K","L","M","N","P","Q",
"R","S","T","U","V","W",
"X","Y","Z");
$l_iNumUppercase = count($l_achUppercase);
$l_aiNumbers = array("1","2","3","4","5","6","7","8","9","0");
$l_iNumNumbers = count($l_aiNumbers);
$l_achSpecialChars = array("!","#","%","@","*","&");
$l_iNumSpecialChars = count($l_achSpecialChars);
$l_astPasswds = array("","","","");
$l_astPasswdSchemes = array("SLUUSLNN","LSUNLLNU","NNUSLLSN","LNLSUNLU");
$l_iNumPasswds = count($l_astPasswdSchemes);
for ($i=0; $i < $l_iNumPasswds; $i++) {
$l_iSchemeLength = strlen($l_astPasswdSchemes[$i]);
$l_achRandLowercase = array_values(array_rand($l_achLowercase, $l_iNumLowercase));
$l_achRandUppercase = array_values(array_rand($l_achUppercase, $l_iNumUppercase));
$l_aiRandNumbers = array_values(array_rand($l_aiNumbers, $l_iNumNumbers));
$l_achRandSpecialChars = array_values(array_rand($l_achSpecialChars, $l_iNumSpecialChars));
for ($j=0; $j < $l_iSchemeLength; $j++) {
$l_chCurrentOne = $l_astPasswdSchemes[$i]{$j};
switch ($l_chCurrentOne) {
case "L":
$l_astPasswds[$i] .= $l_achLowercase[array_shift($l_achRandLowercase)];
break;
case "U":
$l_astPasswds[$i] .= $l_achUppercase[array_shift($l_achRandUppercase)];
break;
case "N":
$l_astPasswds[$i] .= $l_aiNumbers[array_shift($l_aiRandNumbers)];
break;
case "S":
$l_astPasswds[$i] .= $l_achSpecialChars[array_shift($l_achRandSpecialChars)];
break;
default:
break;
}
}
}
return $l_astPasswds;
}
?>
jpinedo
02-Nov-2003 03:15
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";
?>
wazaawazaa600 at msn dot com
15-Oct-2003 02:24
The function go well ever that you work with a simple array. An array of arrays (also called a table), not works with the function correctly. Example:
<?php
$a=array(array(0,1),array(1,2),array(2,3),array(3,4),array(4,5));
echo $a[0][0];echo"<br>";
echo $a[1][0];echo"<br>";
$b=array_rand($a,2);
echo $b[0][0];echo"<br>"; echo $b[1][0];echo"<br>"; ?>
If you are in this situation, you will need to make your own solution.
rick at op8 dot com
03-Jul-2003 05:34
The shuffle() routine works great, far better than array_rand(). Just one small change I'd make, as mt_rand(0, 0) doesn't work:
<?php
$c = count($foo);
for ($i=1; $i<$c; $i++) {
$d = mt_rand(0, $i);
$tmp = $foo[$i];
$foo[$i] = $foo[$d];
$foo[$d] = $tmp;
}
?>
asarnoNOSPAM@interbaun DOT com
24-Jun-2003 01:06
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($originalArray, 1);
$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.
c at aufbix dot org
13-Jun-2003 03:31
If you use array_rand with num_req=1, it will return an integer, and not an array as it would in all other circumstances. You can bypass that like this:
<?php
$randelts=array_rand($feeds,$num);
for ($j=0;$j<count($randelts);$j++) {
if ($num==1) {$subq[$j]=$feeds[$randelts];}
else {$subq[$j]=$feeds[$randelts[$i]]}
}
?>
Paul Hodel (paul at ue dot com dot br)
17-Apr-2003 03:40
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];
}
?>
scandar at home dot se
13-Apr-2003 11:58
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.
mickoz[at]parodius[dot]com
01-Dec-2002 10:28
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); 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);
?>
office at at universalmetropolis dot com
15-Nov-2002 09:54
Once again with PHP, you don't need to get too complicated.
I've had nothing but problems with array_rand() in a baseball management game I'm working on, needing only one entry at random from a list of given choices several times per page.
Instead of array_rand(), I came up with this:
<?php
$teamcolours = array("green","red","orange","blue","purple","grey");
$teamcolours = $teamcolours[rand(0,count($teamcolours))];
print $teamcolours;
?>
it works like a charm.
remember to seed the random generator - srand() - at the top of your script.
a.hole[AT]campbellshaw[DOT]com
23-Jul-2002 01:21
Re:
>lordwolf[at]homewolf[dot]com
>09-May-2002 02:23
>Confirmed...
>I can only get array_rand() to work if the second arg is >= 2.
If the second arg is 1, the function returns a variable instead of an array. I suppose there was a reason for this, but I found it rather confusing and annoying...
So the function does work, but just not in the way you'd assume.
I should imagine you'd be able to sort yourself out with is_array() etc...
dboy at jumpstation dot org
22-Jul-2002 08:58
If you just want to pull one random element from an array, try something like this:
<?php
mt_srand((double) microtime() * 1000000);
$myarray = array("this", "is", "a",
"test", "to", "see",
"if", "I", "can",
"pull", "one", "element",
"from", "an", "array",
"randomly");
$random_index = mt_rand(0, (count($myarray)-1));
?>
Then to test the randomness or what have you try a simple:
<?php
$string = ""; for ($i=0; $i<count($myarray); $i++) {
$random_index = mt_rand(0, (count($myarray)-1));
$string .= "$myarray[$random_index] ";
}
$string = rtrim($string);
echo ($string);
?>
I've gotten extremely good output from this method and would recommend it if you're just pulling one element.
josh at 3io dot com
14-Jun-2002 05:20
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);
$randval and usleep ("0.$randval");
srand ((double) microtime() * 10000000);
$randval = rand();
++$index[$randval % $count];
return $array[$randval % $count];
}
?>
uvm at sun dot he dot net
09-Jul-2001 08:09
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.
martinNOSPAM at franz63 dot de
05-Jul-2001 07:28
If you dont need *serious* random numbers, for e.g. a simple banner rotation you may do something like this:
<br>
$rand_key = date("s") % sizeof($myarray);
<br>
this will rotate through the array every second. It is easier and faster than the random number generator.
<br>You may also use REMOTE_PORT or the Process-Id to get a more randomized number
brooke at jump dot net
03-Mar-2001 06:39
It is true that array_rand() returns with the selected records in the same order as the original array. If you want otherwise, consider shuffle() on the result. Note that there is concern over the correctness of the shuffle() implementation. There exists an O(n) algorithm to shuffle an array thorougly and reliably:
$c = count($foo);
for ($i=0; $i<$c; $i++) {
$d = mt_rand(0, $i);
$tmp = $foo[$i];
$foo[$i] = $foo[$d];
$foo[$d] = $tmp;
}
This, of course, assumes that your keys are sequential and start at zero. If that's not the case, you can use array_keys() to get a sequential map of keys, I think. The rest is left as an excersise.
| |