spacer
downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | conferences | my php.net

search for in the

roundspacer spacer rad2deg
[edit] Last updated: Fri, 15 Mar 2013

view this page in

rand

(PHP 4, PHP 5)

randGenerate a random integer

Description

int rand ( void )
int rand ( int $min , int $max )

If called without the optional min, max arguments rand() returns a pseudo-random integer between 0 and getrandmax(). If you want a random number between 5 and 15 (inclusive), for example, use rand(5, 15).

Note: On some platforms (such as Windows), getrandmax() is only 32767. If you require a range larger than 32767, specifying min and max will allow you to create a range larger than this, or consider using mt_rand() instead.

Parameters

min

The lowest value to return (default: 0)

max

The highest value to return (default: getrandmax())

Return Values

A pseudo random value between min (or 0) and max (or getrandmax(), inclusive).

Changelog

Version Description
4.2.0The random number generator is seeded automatically.

Examples

Example #1 rand() example

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

echo 
rand(515);
?>

The above example will output something similar to:

7771
22264
11

Notes

Caution

This function does not generate cryptographically secure values, and should not be used for cryptographic purposes. If you need a cryptographically secure value, consider using openssl_random_pseudo_bytes() instead.

See Also

  • srand() - Seed the random number generator
  • getrandmax() - Show largest possible random value
  • mt_rand() - Generate a better random value
  • openssl_random_pseudo_bytes() - Generate a pseudo-random string of bytes



roundspacer spacer rad2deg
[edit] Last updated: Fri, 15 Mar 2013
 
spacer add a note User Contributed Notes rand - [52 notes]
up
down
6
phpdev at dunnbypaul dot net
6 years ago
Here's an interesting note about the inferiority of the rand() function. Try, for example, the following code...

<?php
$r
= array(0,0,0,0,0,0,0,0,0,0,0);
for (
$i=0;$i<1000000;$i++) {
 
$n = rand(0,100000);
  if (
$n<=10) {
   
$r[$n]++;
  }
}
print_r($r);
?>

which produces something similar to the following output (on my windows box, where RAND_MAX is 32768):

Array
(
    [0] => 31
    [1] => 0
    [2] => 0
    [3] => 31
    [4] => 0
    [5] => 0
    [6] => 30
    [7] => 0
    [8] => 0
    [9] => 31
    [10] => 0
)

Within this range only multiples of 3 are being selected. Also note that values that are filled are always 30 or 31 (no other values! really!)

Now replace rand() with mt_rand() and see the difference...

Array
(
    [0] => 8
    [1] => 8
    [2] => 14
    [3] => 16
    [4] => 9
    [5] => 11
    [6] => 8
    [7] => 9
    [8] => 7
    [9] => 7
    [10] => 9
)

Much more randomly distributed!

Conclusion: mt_rand() is not just faster, it is a far superior algorithm.
up
down
4
matheus at matheusloureiro dot com
1 month ago
If you are looking for generate a random expression, like password with alphanumeric or any other character, use this function:

<?php
function GeraHash($qtd){
//Under the string $Caracteres you write all the characters you want to be used to randomly generate the code.
$Caracteres = 'ABCDEFGHIJKLMOPQRSTUVXWYZ0123456789';
$QuantidadeCaracteres = strlen($Caracteres);
$QuantidadeCaracteres--;

$Hash=NULL;
    for(
$x=1;$x<=$qtd;$x++){
       
$Posicao = rand(0,$QuantidadeCaracteres);
       
$Hash .= substr($Caracteres,$Posicao,1);
    }

return
$Hash;
}

//Here you specify how many characters the returning string must have
echo GeraHash(30);
?>
up
down
2
Zak
1 year ago
I couldn't find a suitable random alpha-numeric generator function so I rolled my own. It gives a random number in base 36 (0-9, a-z) to a given length.

<?php
function randomAlphaNum($length){

   
$rangeMin = pow(36, $length-1); //smallest number to give length digits in base 36
   
$rangeMax = pow(36, $length)-1; //largest number to give length digits in base 36
   
$base10Rand = mt_rand($rangeMin, $rangeMax); //get the random number
   
$newRand = base_convert($base10Rand, 10, 36); //convert it
   
   
return $newRand; //spit it out

}
?>

hopefully helps someone
up
down
2
relsqui at armory dot com
8 years ago
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).
up
down
1
david [at] ddrewdesign [dot] com
3 years ago
To Jano and Peta:

Thanks for the code. In real world usage, I only had one problem with it: It will never return the first result of the array (or it will return nothing if there's only one item in the array). To remedy this, I simply subtracted 1 from

<?php
$rand
= rand(1,$max);
?>

like so:

<?php
$rand
= rand(1,$max)-1;
?>

Thanks though, for the code you supplied. It was exactly what I needed.
up
down
1
kyle dot florence [@t] gmail dot com
3 years ago
Improved random string generation function:

<?php
// Generate a random character string
function rand_str($length = 32, $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890')
{
   
// Length of character list
   
$chars_length = (strlen($chars) - 1);

   
// Start our string
   
$string = $chars{rand(0, $chars_length)};
   
   
// Generate random string
   
for ($i = 1; $i < $length; $i = strlen($string))
    {
       
// Grab a random character from our list
       
$r = $chars{rand(0, $chars_length)};
       
       
// Make sure the same two characters don't appear next to each other
       
if ($r != $string{$i - 1}) $string .=  $r;
    }
   
   
// Return the string
   
return $string;
}
?>
up
down
3
Alex Khimch alex at khim dot removeit dot ich dot org
1 year ago
Random is NOT actually random.

It is easily illustrated by multiplying rand(1,500) by rand(1,500) and showing the output on the image:

<?php
header
("Content-type: image/png");
$img = imagecreatetruecolor(500,500);

$ink = imagecolorallocate($img,255,255,255);

for(
$i=0;$i<500;$i++) {
  for(
$j=0;$j<500;$j++) {
 
imagesetpixel($img, rand(1,500), rand(1,500), $ink1);
  }
}

imagepng($img);
imagedestroy($img);

?>

I expected to get pixel noise, but instead one can see plain diagonal lines.
up
down
1
liveonaware [at] gmail [dot] com
2 years ago
<?php
//To Pull 7 Unique Random Values Out Of AlphaNumeric

//removed number 0, capital o, number 1 and small L
//Total: keys = 32, elements = 33
$characters = 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",
"1","2","3","4","5","6","7","8","9");

//make an "empty container" or array for our keys
$keys = array();

//first count of $keys is empty so "1", remaining count is 1-6 = total 7 times
while(count($keys) < 7) {
   
//"0" because we use this to FIND ARRAY KEYS which has a 0 value
    //"-1" because were only concerned of number of keys which is 32 not 33
    //count($characters) = 33
   
$x = mt_rand(0, count($characters)-1);
    if(!
in_array($x, $keys)) {
      
$keys[] = $x;
    }
}

foreach(
$keys as $key){
  
$random_chars .= $characters[$key];
}
echo
$random_chars;
?>
up
down
1
Justin Richer
11 months ago
Since many people (myself included) come to this page looking for a way to do a random string, I present a way that uses arrays and shuffle() instead of rand(). This also has the effect of not repeating any characters in the value set.

    $arr = str_split('ABCDEFGHIJKLMNOP'); // get all the characters into an array
    shuffle($arr); // randomize the array
    $arr = array_slice($arr, 0, 6); // get the first six (random) characters out
    $str = implode('', $arr); // smush them back into a string
up
down
0
John Galt
3 years ago
Another way to create an array of random numbers where there are no identical numbers.

($n = number of random numbers to return in the array
$min = minimum number
$max = maximum number)

<?php
 
function uniqueRand($n, $min = 0, $max = null)
 {
  if(
$max === null)
  
$max = getrandmax();
 
$array = range($min, $max);
 
$return = array();
 
$keys = array_rand($array, $n);
  foreach(
$keys as $key)
  
$return[] = $array
gipoco.com is neither affiliated with the authors of this page nor responsible for its contents. This is a safe-cache copy of the original web site.