rand

(PHP 3, PHP 4, PHP 5)

rand -- 产生一个随机整数

说明

int rand ( [int min, int max] )

如果没有提供可选参数 minmaxrand() 返回 0 到 RAND_MAX 之间的伪随机整数。例如想要 5 到 15(包括 5 和 15)之间的随机数,用 rand(5, 15)

例子 1. rand() example

<?php
echo rand() . "\n";
echo
rand() . "\n";

echo
rand(5, 15);
?>

上例的输出类似于:

7771
22264
11

注: 在某些平台下(例如 Windows)RAND_MAX 只有 32768。如果需要的范围大于 32768,那么指定 minmax 参数就可以生成大于 RAND_MAX的数了,或者考虑用 mt_rand() 来替代之。

注: 自 PHP 4.2.0 起,不再需要用 srand()mt_srand() 函数给随机数发生器播种,现已自动完成。

注: 在 3.0.7 之前的版本中,max 的含义是 range。要在这些版本中得到和上例相同 5 到 15 的随机数,简短的例子是 rand (5, 11)

参见 srand()getrandmax()mt_rand()


add a note add a note User Contributed Notes
thebomb-hq [AT] gmx [DOT] de
03-Apr-2006 11:48
very easy function to generate keys without substr:

<?php

 
function randomkeys($length)
  {
  
$pattern = "1234567890abcdefghijklmnopqrstuvwxyz";
   for(
$i=0;$i<$length;$i++)
   {
    
$key .= $pattern{rand(0,35)};
   }
   return
$key;
  }

  echo
randomkeys(8),"<br>";
  echo
randomkeys(16),"<br>";
  echo
randomkeys(32),"<br>";
  echo
randomkeys(64),"<br>";

?>

output:

n94bv1h7
y9qi1qu2us3wged2
00dhax4x68028q96yyoypizjb2frgttp
478d4ab0ikapaiv0hk9838qd076q1yf46nh0ysigds6ob2xtl61odq2nx8dx7t2b
RichardBronosky (1st at last dot com)
03-Mar-2006 07:01
I think what jeswanth was shooting for was something like:

php -n -r '
//<?php
$chars
= 3;
$length= 6;
while(
count($nums) < $chars) $nums[rand(0,9)] = null;
while(
strlen($code) < $length) $code .= array_rand($nums);
echo
"\ncode: $code\n\n";
//?>
'

(No need to create a file.  Just paste that in a terminal to test.)

with $chars = 3 you get codes like:
007277
429942
340343

with $chars = 2 you get codes like:
424244
666161
112122

Now I just have to come up with a use for it!
jon at zerogen dot co dot uk
09-Feb-2006 01:50
I know the code is a bit crappy but i use this to generate a random code

$acceptedChars = 'azertyuiopqsdfghjklmwxcvbnAZERTYUIOPQSDFGHJKLMWXCVBN0123456789';
  $max = strlen($acceptedChars)-1;
  $code1 = null;
  for($i=0; $i < 6; $i++) {
   $code1 .= $acceptedChars{mt_rand(0, $max)};
}

$ttcode1 = $code1 . $email . time();
$ttcode2 = md5($ttcode1);
$ttcode = substr($ttcode2,0,10);

it grabs a random 6 digit code, then adds the email address and the time stamp, md5 all of that then i've got a unique code
AlieN
25-Jan-2006 06:48
About selecting random row from a MySQL table (much faster thand MySQL's rand function:

$tot=mysql_fetch_row(mysql_query("SELECT COUNT(*) FROM `sometable` WHERE (condition)"));
$row=rand(0,$tot);
$res=mysql_fetch_row(mysql_query("SELECT * FROM `sometable` WHERE (condition) LIMIT $row,1"));
a dot tietje at flynet dot de
20-Jan-2006 09:54
@ mozzer:

The only difference ist that your code does not allow codes < 100000. Try

$num = sprintf ('%06d', rand(0, 999999));
mozzer at mozzers dot com
19-Jan-2006 04:35
In reply to jeswanth...

There is absolutely no difference between what you just posted and any random 6 digit number.

<?php
$num
= rand(100000, 999999);
$code = $num;
echo
"$code";
?>
jeswanth at gmail dot com
29-Dec-2005 02:49
Hi all, I wish that following code might be usefull for you. Rand() can be used to generate unique userfriendly codes. For example if you want to give each user a code that can be easily rememberd. Rand() surprisingly generates userfriendly codes when used like this,

<?php
$num
= rand(0, 9);
$num1 = rand(0, 9);
$num2 = rand(0, 9);
$num3 = rand(0, 9);
$num4 = rand(0, 9);
$num5 = rand(0, 9);
$code = $num . $num1 . $num2 . $num3 . $num4 . $num5;
echo
"$code";
?>

When you run this code, you can see the generated number is easiy to remember.
RichardBronosky (1st at last dot com)
14-Dec-2005 02:40
I like the idea of expertphp at y!, but the implementation was too expensive for my load.  Here is the tightest solution to generating $x random [[:alnum:]] chars that I could think of.  I use this for creating random file names.

<?php
// Assuming $z is "_file_prefix_" or an empty string.
// If $z is unset an E_NOTICE will be added to your logs.
// That's bad for production boxes!
for($x=0;$x<32;$x++){
 
$y = rand(0,61);
 
$z .= chr( $y + (($y<10) ? 48 : (($y<36) ? 55 : 61)) );
}
echo
$z;
?>

To get an array, just change this line:
<?php
 
// $z can be unset, null, or an existing array.  E_ERROR if it's a string.
 
$z[] = chr( $y + (($y<10) ? 48 : (($y<36) ? 55 : 61)) );
?>
pitilezard at gmail dot com
12-Oct-2005 07:25
Kniht: for a oneline style you can also do :

function rand_array($size,$min,$max) {
   $v = array();
   for ($i=0; $i<$size; $v[$i]=$n=rand($min,$max), $c=array_count_values($v), $i=$i+(($c[$n]==1)?1:0));
   return $v;
}
expertphp at yahoo dot com
08-Oct-2005 09:50
Generate custom random characters. By default, allwed characters are [0-9][a-z][A-Z]. Optional, you can generate only with numeric or/and not numeric characters.
For more informations, please visit: http://expert.no-ip.org/?free=Random&class

<?php

require_once 'Random.php';
 
// generate 3 default random characters
$obj1 = new Random;
echo
$obj1->get(3)."<br />\n";
 
// generate 4 custom [abcdefgh] random characters
$obj2 = new Random("abcdefgh");
echo
$obj2->get(4)."<br />\n";
 
// generate 6 default random characters
// with only numeric and not numeric character(s)
// this option is useful to generate a custom password
$obj3 = new Random(false, true, true);
echo
$obj3->get(6)."<br />\n";
// generate another 12 random characters with $obj3 options
echo $obj3->get(12);
 
?>

Output results :

0x9
ebgc
aBAB0d
5X6Sfo0Cui6J
frank
05-Oct-2005 07:40
re: Kniht

a little change to avoid a closed loop:

function rand_array($size, $min, $max) {
   if ($size > $max)
       $size = $max;
   $v = array();
   while ( count($v) < $size ) {
       do {
           $n = rand( $min, $max );
       } while ( array_search($n, $v) !== false);
           $v[] = $n;
   }
   return $v;
}
Kniht
28-Sep-2005 05:53
RE: nick at nerdynick dot com

<?php
function rand_array( $size, $min, $max ) {
 
$v = array();
  while (
count($v) < $size ) {
   do {
    
$n = rand( $min, $max );
   } while (
array_search( $n, $v ) !== false );
  
$v[] = $n;
  }
  return
$v;
}
?>
nick at nerdynick dot com
18-Sep-2005 11:58
Here is a function I wrote to generate an array with a unigue set of numbers in each place. You can enter the Min and the Max number to pick from and the number of array places to generate for.

random_loop([# of Array Places], [Min], [Max]);

<?php
$cols
= random_loop(9, 0, 9);

function
random_loop($num, $min, $max){
  
$rand[0] = mt_rand($min, $max);
   for(
$i = 1; $i<$num; $i++){
       do{
          
$check = true;
          
$rand[$i] = mt_rand($min, $max);
           for(
$ii = 0; $ii < (count($rand)-1); $ii++){
               if(
$rand[$i] == $rand[$ii] && $check){
                  
$check = false;
                   break;
               }
           }
       }while (!
$check);
   }
   return
$rand;
}

?>

Enjoy and use at your will.
Viking Coder
14-Sep-2005 03:21
To mark at mmpro dot de, or anybody else wanting a unique list of random numbers in a given range.

$min=1;
$max=10;
$count=5;

$list=range($min,$max);
shuffle($list);
$list=array_slice($list,0,$count);

andy at andycc dot net, this can also be used to generate random strings.

$length=8;

$list=array_merge(range('a','z'),range(0,9));
shuffle($list);
$string=substr(join($list),0,$length);
andy at andycc dot net
29-Aug-2005 03:12
Regarding my previous post / function - there's an error in the "for" loop declaration, the correct line should be:

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

the previous posted line would generate a string that is 1 character longer than the given $length.  This corrects that problem.
andy at andycc dot net
29-Aug-2005 01:15
Need a string of random letters and numbers for a primary key/session ID? 
Here's a dead simple function that works pretty efficiently.

Set $template to a string of letters/numbers to choose from
(e.g. any of the letters in this string can be returned as part of the unique ID - could use symbols etc.)

Then call GetRandomString(?) with an integer value that defines how long you want the string to be.

<?php

// Andy Shellam, andy [at] andycc [dot] net

// generate a random string of numbers/letters

settype($template, "string");

// you could repeat the alphabet to get more randomness
$template = "1234567890abcdefghijklmnopqrstuvwxyz";

function
GetRandomString($length) {

       global
$template;

      
settype($length, "integer");
      
settype($rndstring, "string");
      
settype($a, "integer");
      
settype($b, "integer");
      
       for (
$a = 0; $a <= $length; $a++) {
              
$b = rand(0, strlen($template) - 1);
              
$rndstring .= $template[$b];
       }
      
       return
$rndstring;
      
}

echo
GetRandomString(30);

?>

This is the output after running the script 5 times:

i7wwgx8p1x0mdhn6gnyqzcq3dpqsc0
5ntlvapx6o90notob4n7isdp0ohp19
ojnyuile9y459cjr1vf9kgdas4tscw
2fr5dqn62kzfjvywqczjaoyrqjeyfd
9dtnk7e18jjx1og4gr4noznldit0ba

The longer and more varied the text of $template, the more random your string will be,
and the higher the value of GetRandomString(?), the more unique your string is.

Note also, if you pass a non-integer into the function, the settype($length) will force it to be 0,
hence you won't get anything returned, so make sure you pass it a valid integer.
Pierre C.
25-Aug-2005 07:27
I am sorry to tell you this, mark at mmpro dot de, but the function you mentioned looks awfully and unnecessarily slow to me:

At each iteration, you have to check if the generated number is not already in the list, so you end up with a complexity of O(n)... at best! (In the worst case, the algorithm might just run forever!!!)

----

Here is a better (and safer!) way to generate a random array of different numbers:

  - First generate an array, each element filled with a different value (like: 1,2,3,4,5,...,n)

  - Then shuffle your array. In other words, swap each element in your array with another randomly-chosen element in the array.

Now the algorithm has a complexity of O(n), instead of the original O(n).

----

The generation of the array of values is left at the discretion of the programmer (it is down to his/her needs to determine how the values should be reparted).

The shuffling of the array should go like this (WARNING: CODE NOT TESTED !!!):

$length = count($array) ;

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

  // Choosing an element at random
  $randpos = rand(0, $length-1) ;

  // Swapping elements
  $temp = $array[$randpos] ;
  $array[$randpos] = $array[$i] ;
  $array[$i] = $temp ;
}

return $array ;
Corry Gellatly ncl.ac.uk
14-Jul-2005 01:00
I need to generate large arrays of random numbers within specific ranges. The function provided by mark at mmpro dot de is good stuff, but if the range of your random numbers ($max - $min) is less than the number of elements in the array ($num), i.e. you want to permit duplicate values, then:

Alter this line:

 while (in_array($a,$ret));

to this:

 while (next($ret));
mark at mmpro dot de
08-Jul-2005 10:14
I needed to generate a random array of different(!) numbers, i.e. no number in the array should be duplicated. I used the nice functions from phpdeveloper AT o2 DOT pl but it didn't work as I thought.

So I varied it a little bit and here you are:

function RandomArray($min,$max,$num) {

$ret = array();

// as long as the array contains $num numbers loop
while (count($ret) <$num) {
   do {
       $a = rand($min,$max);
       //
       #echo $a."<br />";
   }
   // check if $a is already in the array $ret
   // if so, make another random number
   while (in_array($a,$ret));
   // add the new random number to the end of the array
   $ret[] = $a;
}
return($ret);

}

// generate an array of 3 numbers between 10 and 19
$ret = randomArray(10,19,3)

echo $ret[0]."-".$ret[1]."-".$ret[2];
ruku
05-Jul-2005 08:04
[quote]SELECT * FROM tablename WHERE id>='$d' LIMIT 1[/quote]

typo: $d should be $id

^^
Corry Gellatly ncl.ac.uk
04-Jul-2005 11:17
I've used this script to generate an array of random numbers with a numeric key. I got an array of over 200,000 on this system, and got <1000 using the examples submitted previously. I haven't managed to return the array variable outside the function, but have written it to a database.

<?php
function rand_array($start, $end, $rangemin, $rangemax)
{
$array = array_fill($start, $end, 1);

   foreach(
$array as $key => $value)
       {
      
$value = rand($rangemin,$rangemax);
       print
"$key: $value<br>\n";
       }
}

$start = 1;
$end = 1000;
$rangemin = 1;
$rangemax = 20000;

rand_array($start, $end, $rangemin, $rangemax);
?>
roger at kleverNOSPAM dot co dot uk
27-Jun-2005 09:28
umpalump's post was very helpful, thankyou.
Since random_0_1() can return 0, I would suggest replacing
<? $x = random_0_1(); ?>
with 
<? while (!$x) $x = random_0_1(); ?>
to avoid an error when performing log($x)
emailfire at gmail dot com
21-Jun-2005 10:39
To get a random quote in a file use:

<?
$file
= "quotes.txt";
$quotes = file($file);
echo
$quotes[rand(0, sizeof($quotes)-1)];
?>

quotes.txt looks like:

Quote 1
Quote 2
Quote 3
Quote 4
umpalump at poczta dot neostrada dot pl
13-Jun-2005 08:32
Random numbers with Gauss distribution (normal distribution).
A correct alghoritm. Without aproximations, like Smaaps'
It is specially usefull for simulations in physics.
Check yourself, and have a fun.

<?php

function gauss()
// N(0,1)
   // returns random number with normal distribution:
   //  mean=0
   //  std dev=1
  
   // auxilary vars
  
$x=random_0_1();
  
$y=random_0_1();
  
  
// two independent variables with normal distribution N(0,1)
  
$u=sqrt(-2*log($x))*cos(2*pi()*$y);
  
$v=sqrt(-2*log($x))*sin(2*pi()*$y);
  
  
// i will return only one, couse only one needed
  
return $u;
}

function
gauss_ms($m=0.0,$s=1.0)
// N(m,s)
   // returns random number with normal distribution:
   //  mean=m
   //  std dev=s
  
  
return gauss()*$s+$m;
}

function
random_0_1()
// auxiliary function
   // returns random number with flat distribution from 0 to 1
  
return (float)rand()/(float)getrandmax();
}

?>

JanS
student of astronomy
on Warsaw University
smaaps at kaldamar dot de
07-Jun-2005 01:44
Lately I needed some random numbers with a gaussian (normal) distribution, not evenly distributed as the numbers generated by rand(). After googling a while, I found out that there is no perfect algrorithm that creates such numbers out of evenly distruted random numbers but a few methods that have similar effect. The following function implements all three algorithms I found- The the last two methods create numbers where you can find a lower and upper boundary and the first one will create a number from time to time (such as one in every 10000) that may be very far from the average value. Have fun testing and using it.

function gauss($algorithm = "polar") {
   $randmax = 9999;
  
   switch($algorithm) {
      
       //polar-methode by marsaglia
       case "polar":
           $v = 2;
           while ($v > 1) {
               $u1 = rand(0, $randmax) / $randmax;
               $u2 = rand(0, $randmax) / $randmax;

               $v = (2 * $u1 - 1) * (2 * $u1 - 1) + (2 * $u2 - 1) * (2 * $u2 - 1);
           }
          
           return (2* $u1 - 1) * (( -2 * log($v) / $v) ^ 0.5);
      
       // box-muller-method
       case "boxmuller":
           do {
               $u1 = rand(0, $randmax) / $randmax;
               $u2 = rand(0, $randmax) / $randmax;                   
              
               $x = sqrt(-2 * log($u1)) * cos(2 * pi() * $u2);
           } while (strval($x) == "1.#INF" or strval($x) == "-1.#INF");
          
           // the check has to be done cause sometimes (1:10000)
           // values such as "1.#INF" occur and i dont know why
          
           return $x;

       // twelve random numbers 
       case "zwoelfer":
           $sum = 0;
           for ($i = 0; $i < 12; $i++) {
               $sum += rand(0, $randmax) / $randmax;
           }
           return $sum;
     }     
}
uoseth at gmail dot com
29-May-2005 12:47
If you really want to the kye to have 40 chars, you must use
for ($i=0;$i<=$length;$i++) and not
for ($i=0;$i<$length;$i++) ... there it is with the detail added

<?
// RANDOM KEY PARAMETERS
$keychars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$length = 40;

// RANDOM KEY GENERATOR
$randkey = "";
$max=strlen($keychars)-1;
for (
$i=0;$i<=$length;$i++) {
 
$randkey .= substr($keychars, rand(0, $max), 1);
}
?>
cmol at cmol dot dk
26-May-2005 12:23
Made this random keygen function.

It's totally random.. And you can set the number of characters as you use it...

<?php

function keygen($max){

$items = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
$x = 1;
$total = strlen($items) - 1;

while(
$x <= $max){

$rand = rand(0, $total);

$item = substr($items, $rand, 1);
if(
$x == 1){
$key = $item;
}
elseif(
$x > 1)
{
$key .= $item;
}
$x++;
}

echo
$key;
}
$number = 10;
echo
keygen($number);
?>

You can change the "items" as you like...
snecx at yahoo dot com
25-May-2005 02:00
There was some typo in the previous post. Here is a correct one (tested).

<?php

$length   
= 16;
$key_chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
$rand_max  = strlen($key_chars) - 1;

for (
$i = 0; $i < $length; $i++)
{
  
$rand_pos  = rand(0, $rand_max);
  
$rand_key[] = $key_chars{$rand_pos};
}

$rand_pass = implode('', $rand_key);

echo
$rand_pass;

?>
snecx at yahoo dot com
25-May-2005 01:57
The following would be a much cleaner code to produce a nice random password. The substr function is removed.

<?php

$length   
= 16;
$key_chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
$rand_max  = strlen($keychars) - 1;

for (
$i = 0; $i < $length; $i++)
{
  
$rand_pos  = rand(0, $max);
  
$rand_key[] = $key_chars{$rand_pos};
}

$rand_pass = implode('', $rand_key);

echo
$rand_pass;

?>
Gavin
11-May-2005 05:30
There is one problem with Luis and Goochivasquez's code.  substr starts at 0 not one, so the string is 0-39 not 1-40.  This means that substr would return false sometimes and would give you a length smaller than expected.

Here's a fix:

// RANDOM KEY PARAMETERS
$keychars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$length = 40;

// RANDOM KEY GENERATOR
$randkey = "";
$max=strlen($keychars)-1;
for ($i=0;$i<$length;$i++) {
  $randkey .= substr($keychars, rand(0, $max), 1);
}
Luis
04-May-2005 11:57
In fact, goochivasquez's methos also returns a concrete length key (40 chars in this case). Why not...

// RANDOM KEY PARAMETERS
$keychars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$length = rand(8,40);

// RANDOM KEY GENERATOR
$randkey = "";
for ($i=0;$i<$length;$i++)
{
  $randkey .= substr($keychars, rand(1, strlen($keychars) ), 1);
}
cezden
28-Apr-2005 04:29
Jawsper,

the problem is that in your method you get not more than

 RAND_MAX

'random' strings. (in fact they are not random in the set of all strings of given length) It's rather poor result when compared with goochivasquez's

strlen($keychars)^$length

number of strings.

In other words - it's little bit less complicated but far, far from achieving the goal.

cezden
jawsper
22-Apr-2005 03:33
why so complicated?

this works fine for me:

<?php
function randomstring($length) {
  
$random = rand();
  
$string = md5($random);
  
$output = substr($string,$length);
   return
$output;
}
?>
goochivasquez -at- gmail
16-Apr-2005 06:53
Following script generates a random key of characters and numbers. Handy for random logins or verifications.

***
// RANDOM KEY PARAMETERS
$keychars = "abcdefghijklmnopqrstuvwxyz0123456789";
$length = 40;

// RANDOM KEY GENERATOR
$randkey = "";
for ($i=0;$i<$length;$i++)
  $randkey .= substr($keychars, rand(1, strlen($keychars) ), 1);
hoffa at NOSPAM hoffa.se
31-Mar-2005 07:19
To shuffle an array ( [0....n] )

function Shufflearr($array) {
   $size = sizeof($array) - 1;
   for ($x = 0; $x < $size; $x++) {
       $i = rand($x, $size);
       $tmp = $array[$x];
       $array[$x] = $array[$i];
       $array[$i] = $tmp;
   }
   return $array;
}

// create an array
for ($i=0; $i<10; $i++) {
   $nbrarray[$i] = $i;
}

print_r($nbrarray); // before
$nbrarray = Shufflearr($nbrarray); // shuffle
print_r($nbrarray); // after
Sam Fullman
10-Mar-2005 12:55
Quick simple way to generate a random n-length key with this function:

function create_key($len){
   for($i=1;$i<=$len;$i++)$str.=base_convert( rand(0,15),10,16);
   return $str;
}
echo create_key(32);
ferconstantino at hotmail dot com
28-Feb-2005 04:19
RANDOM ARRAY (all different numbers)

This is a new version of a function published in this forum:

function GetRandomArray($min,$max,$num) {
  
   #data check
   $range = 1 + $max - $min;
   if ($num > $range) return false;
   if ($num < 1) return false;
  
   #data prep
   $result = array();
   $count = 0;
   $currentnum = 0; 
  
   #loop me baby ;-)
   while(count($result) < $num) {
         $currentnum = rand($min,$max);
         if (!in_array($currentnum,$result)){
               $result[$count] = $currentnum;
       $count++;
         }
   }
  
   return $result;
}
horroradore at gmail dot com
25-Feb-2005 12:03
Here's the simplest way I've found to get random something without the need for an external file. Simple, but effective.

<?php
 
function func(){
 
//Randomize selection. In this case, 5 (0,1,2,3,4,5).
 
$x = rand()&4;
 
$vars = array(
  
//Insert your data into array.
  
0 => "var1",
  
1 => "var2",
  
2 => "var3",
  
3 => "var4",
  
4 => "var5"
 
);
  echo
$vars[$x];
 }
?>

The only problem with that is that it's not really random, and that you sometimes get the same result several times. I've seen sollutions to this using microtime(), but I can't think of them off the top of my head.
phpdeveloper AT o2 DOT pl
15-Feb-2005 11:29
This is most simple random array generator, hope zo ;-)
Moreover it uses some PHP array features :-), and does not search through array haystack, just checks for data if its set :P.

<?php

function GetRandomArray($min,$max,$num) {
  
  
#data check
  
$range = 1 + $max + $min;
   if (
$num > $range) return false;
   if (
$num < 1) return false;
  
  
#data prep
  
$result = array();
  
$a = rand($min,$max);
  
$result[$a] = $a;
  
  
#loop me baby ;-)
  
while(count($result) < $num) {
       do {
$a = rand($min,$max); } while(isset($result[$a]));
      
$result[$a] = $a;
   }
  
   return
$result;
}

var_dump(GetRandomArray(3,10,5));
?>

nice coding 4 U all :-)
[k3oGH]
13-Feb-2005 02:34
<?php
//A way to make random quotes.
$file="quotefile.txt";
$file=file($file);
$count=count($file);
$i=0;

$rand=rand($i, $count);
echo
$rand;

//this will output a random line in a textfile called quotefile.txt
?>
php dot net at dannysauer dot com
09-Feb-2005 10:47
Actually, if you want 2 different random numbers, you should probably use a while loop.  This is quicker and doesn't have the possibility of running into a recursive function limit.

<?php
function fn_arrRandom($min, $max){
  
// generate two random numbers
  
$iRandom1 =0;
  
$iRandom2 = 0;
  
// compare them
  
while ($iRandom1 == $iRandom2){
      
// the numbers are equal, try again
      
$iRandom1 = rand($min, $max);
      
$iRandom2 = rand($min, $max);
   }
  
// they're not equal - go ahead and return them
  
return array($iRandom1, $iRandom2);
}

print_r(fn_arrRandom(3, 13));
?>

At that point, we may as well write a function that returns an arbitrary number of differing random numbers:

<?php
function random_array($min, $max, $num){
  
$range = 1+$min-$max;
  
// if num is bigger than the potential range, barf.
   // note that this will likely get a little slow as $num
   // approaches $range, esp. for large values of $num and $range
  
if($num > $range){
     return
false;
   }
  
// set up a place to hold the return value
  
$ret = Array();
  
// fill the array
  
while(count($ret)) < $num){
    
$a = false; // just declare it outside of the do-while scope
     // generate a number that's not already in the array
     // (use do-while so the rand() happens at least once)
    
do{
        
$a = rand($min, $max);
     }while(
in_array($ret, $a));
    
// stick the new number at the end of the array
    
$ret[] = $a;
   }
   return
$ret;
}

print_r(random_array(3, 13, 5));
?>
tech_niek at users dot sourceforge dot net
09-Feb-2005 04:50
If you want to generate two +different+ random numbers in the same range:
<?
function fn_arrRandom($min, $max){

  
// generate two random numbers
  
$iRandom1 = rand($min, $max);
  
$iRandom2 = rand($min, $max);
  
  
// compare them
  
if ($iRandom1 !== $iRandom2){
      
// the numbers are different, great
  
} else {
      
// the numbers are equal, try again
      
return fn_arrRandom($min, $max);
   }
   return array(
$iRandom1, $iRandom2);
}

print_r(fn_arrRandom(3, 13));
?>

The above will output two different random numbers in an array:
 Array ( [0] => 5 [1] => 7 )
polmme at hotmail dot com
03-Feb-2005 07:10
Why not just like this....

<?

//author: polmme

$codelenght = 10;
while(
$newcode_length < $codelenght) {
$x=1;
$y=3;
$part = rand($x,$y);
if(
$part==1){$a=48;$b=57;}  // Numbers
if($part==2){$a=65;$b=90;}  // UpperCase
if($part==3){$a=97;$b=122;} // LowerCase
$code_part=chr(rand($a,$b));
$newcode_length = $newcode_length + 1;
$newcode = $newcode.$code_part;
}
echo
$newcode;
?>
webdude at sider dot net
27-Jan-2005 11:32
A very simple random string generator function:

<?
function rand_str($size)
{
  
$feed = "0123456789abcdefghijklmnopqrstuvwxyz";
   for (
$i=0; $i < $size; $i++)
   {
      
$rand_str .= substr($feed, rand(0, strlen($feed)-1), 1);
   }
   return
$rand_str;
}

echo
rand_str(10);
?>
relsqui at armory dot com
21-Jan-2005 06:23
Don't forget, it's faster to use bitwise operations when you need a random number that's less than some power of two. For example,

<?php
rand
()&1;
// instead of
rand(0,1);
// for generating 0 or 1,

rand()&3;
// instead of
rand(0,3);
// for generating 0, 1, 2, or 3,

rand()&7;
// instead of
rand(0,7)
// for generating 0, 1, 2, 3, 4, 5, 6, or 7,
?>

and so on. All you're doing there is generating a default random number (so PHP doesn't have to parse any arguments) and chopping off the piece that's useful to you (using a bitwise operation which is faster than even basic math).
Janus - palacecommunity dot com
29-Dec-2004 10:03
Or you could do!:

$rnd = mysql_result(mysql_query("SELECT FLOOR(RAND() * COUNT(*)) FROM `table` (WHERE `condition`)"));

mysql_query("SELECT * FROM `table` (WHERE condition`) LIMIT {$rnd},1");
onno at onnovanbraam dot com
12-Sep-2004 09:58
>>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.<<

Do realize that you don't HAVE to call srand, but if you don't you get the same results every time... Took me quite a while to get to that conclusion, since I couldn't figure it out:

foreach($Unit AS $index => $value) {
   srand() ;
   $rand_pos_x = rand(0, $EVAC['x_max']) ;
   $rand_pos_y = rand(0, $EVAC['y_max']) ;
}

works, but:

foreach($Unit AS $index => $value) {
   $rand_pos_x = rand(0, $EVAC['x_max']) ;
   $rand_pos_y = rand(0, $EVAC['y_max']) ;
}

doesnt even though they say it should.

I'm using Windows XP Pro (Windows NT EVOLUTION 5.1 build 2600), PHP Version 4.3.3, CGI/FastCGI.
aidan at php dot net
11-Sep-2004 03:45
To easily generate large numbers, or random strings such as passwords, take a look at the below function.

http://aidan.dotgeek.org/lib/?file=function.str_rand.php
a_kunyszSPAM at SUXyahoo dot com
04-Sep-2004 10:44
You won't get true random numbers from a computer but you can get some from a webcam or radioactive material.

http://www.fourmilab.ch/hotbits/ (you can fetch random bits generated from radioactive material from the web here)
http://www.lavarnd.org/ (how to set up a random number generator with a webcam)
jbarbero at u dot washington dot edu
09-Dec-2003 05:14
to jordan at do not spam .com:

The image no-cache function is simpler if you just do:
<?
$junk
= md5(time());
?>

Usage would be: <img src="image.gif?<?=$junk?>">

md5(time()) is more guaranteed to be unique, and it is faster than two md5 calls.
ewspencer at industrex dot com
04-Jun-2003 02:40
Inspired by the many useful tips posted by other users, I wrote a flexible, arbitrary, random character generator, which also produces random color values in decimal or hexadecimal format.

The procedure is encapsulated as a PHP function named randchar().

You're welcome to freely download the randchar() source code at http://www.industrex.com/opensource/randchar.phps
igge at netpond dot com
30-Oct-2002 08:35
About selecting random rows from a MySQL table:

SELECT * FROM tablename ORDER BY RAND() LIMIT 1

works for small tables, but once the tables grow larger than 300,000 records or so this will be very slow because MySQL will have to process ALL the entries from the table, order them randomly and then return the first row of the ordered result, and this sorting takes long time. Instead you can do it like this (atleast if you have an auto_increment PK):

SELECT MIN(id), MAX(id) FROM tablename;

Fetch the result into $a

$id=rand($a[0],$a[1]);

SELECT * FROM tablename WHERE id>='$d' LIMIT 1