rand function returns just a whole numbers. If you want a random float, then here's an elegant way:
<?php
function random_float ($min,$max) {
return ($min+lcg_value()*(abs($max-$min)));
}
?>
rand
(PHP 4, PHP 5)
rand — Erzeugt einen zufälligen Integerwert
Beschreibung
Liefert eine Pseudozufallszahl zwischen min und max (inklusive), oder zwischen 0 und get_randmax() falls keine Parameter angegeben wurden. Wenn Sie z.B. einen Zufallswert zwischen 5 und 15 benötigen so wäre der Aufruf dafür rand(5, 15).
Hinweis: Auf manchen Plattformen (Windows z.B.) ist get_randmax() nur 32768. Wenn sie einen größeren Wertebereich benötigen sollten, so können Sie entweder einen größeren max-Wert übergeben oder besser die mt_rand()-Funktion anstelle von rand() einsetzen.
Hinweis: Seit PHP 4.2.0 besteht keine Notwendigkeit mehr, den Zufallsgenerator für Zahlen mit srand() oder mt_srand() zu füttern, das geschieht nun automatisch.
Parameter-Liste
- min
-
Der niedrigste zurückzugebende Wert (Vorgabe: 0)
- max
-
Der höchste zurückzugebende Wert (Vorgabe: get_randmax())
Rückgabewerte
Ein Pseudozufallswert zwischen min (oder 0) und max (oder get_randmax(), inklusive).
Changelog
| Version | Beschreibung |
|---|---|
| Seit 3.0.7 | In Versionen vor 3.0.7 war die Bedeutung von max statt dessen range. Um in diesen Versionen das gleiche Ergebnis zu erzielen muss im folgenden Beispiel rand (5, 11) benutzt werden um eine Zufallszahl zwischen 5 und 15 zu erhalten. |
Beispiele
Beispiel #1 rand() example
<?php
echo rand() . "\n";
echo rand() . "\n";
echo rand(5, 15);
?>
Das oben gezeigte Beispiel erzeugt eine ähnliche Ausgabe wie:
7771 22264 11
Siehe auch
- srand() - Anfangswert für Zufallsgenerator festlegen
- getrandmax() - Liefert die maximale Zufallszahl
- mt_rand() - Erzeugt "bessere" Zufallszahlen
rand
16-Jun-2007 09:43
24-May-2007 02:36
Note that the automatic seeding seems to be done with the current number of seconds which means you can get the same results for several runs on a fast server. Either call srand() yourself with a more frequently changing seed or use mt_rand() which doesn't appear to suffer from the problem.
29-Apr-2007 05:24
DKDiveDude forgot one thing in his function.
I tested it, and I found out the random output could even be smaller then $intMin.
This was because he forgot to multiply $intMin with $intPowerTen.
Below DKDiveDude's function with the edit
<?php
// Floating point random number function
// April 2007, René W. Feuerlein
function fprand($intMin,$intMax,$intDecimals) {
if($intDecimals) {
$intPowerTen=pow(10,$intDecimals);
return rand($intMin*$intPowerTen,$intMax*$intPowerTen)/$intPowerTen;
}
else
return rand($intMin,$intMax);
}
?>
27-Apr-2007 05:44
I was kind of surprised that PHP did not have a built-in floating point random number function. So I created my own:
<?
// Floating point random number function
// April 2007, René W. Feuerlein
function fprand($intMin,$intMax,$intDecimals) {
if($intDecimals) {
$intPowerTen=pow(10,$intDecimals);
return rand($intMin,$intMax*$intPowerTen)/$intPowerTen;
}
else
return rand($intMin,$intMax);
}
// Example of fprand function
for($i=0; $i<=5; $i++) {
echo "Three random numbers with $i decimals are: ";
for($ii=1; $ii<=3; $ii++)
echo fprand(1,10,$i).' ';
echo '<br>';
}
?>
12-Apr-2007 07:50
A very useful function for creating key with a lot of flexibility to control the type of characters used in your key
you can add your custom type of character limitations to it by adding a custom preg_match according to your liking
Enjoy
<?php
/**
* Key Generator
*
* @param int Length of the key
* @param string Type of Character
* (lower, upper, numeric, ALPHA, ALNUM)
*
* @return string Generated key from the arguments
*/
function mKey($len = 12, $type = 'ALNUM')
{
// Register the lower case alphabet array
$alpha = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z');
// Register the upper case alphabet array
$ALPHA = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z');
// Register the numeric array
$num = array('1', '2', '3', '4', '5', '6', '7', '8', '9', '0');
// Initialize the keyVals array for use in the for loop
$keyVals = array();
// Initialize the key array to register each char
$key = array();
// Loop through the choices and register
// The choice to keyVals array
switch ($type)
{
case 'lower' :
$keyVals = $alpha;
break;
case 'upper' :
$keyVals = $ALPHA;
break;
case 'numeric' :
$keyVals = $num;
break;
case 'ALPHA' :
$keyVals = array_merge($alpha, $ALPHA);
break;
case 'ALNUM' :
$keyVals = array_merge($alpha, $ALPHA, $num);
break;
}
// Loop as many times as specified
// Register each value to the key array
for($i = 0; $i <= $len-1; $i++)
{
$r = rand(0,count($keyVals)-1);
$key[$i] = $keyVals[$r];
}
// Glue the key array into a string and return it
return join("", $key);
}
?>
If you have any questions or comments feel free to contact me
07-Apr-2007 06:28
Update on Anne's function.
$pattern holds 36 characters and therefor rand should pick index numbers between 0 and 35.
Updated function:
<?php
function randomkeys($length)
{
$pattern = "1234567890abcdefghijklmnopqrstuvwxyz";
$key = $pattern{rand(0,35)};
for($i=1;$i<$length;$i++)
{
$key .= $pattern{rand(0,35)};
}
return $key;
}
?>
05-Apr-2007 12:42
isn't this just a simpler way of making a random id for somthing? I mean i know that there is a very slight chance that a duplicate could be made but its a very, very, very small chance, nearly impossible.
$rand = mt_rand(0, 32);
$code = md5($rand . time());
echo "$code";
and if you don't want it the md5 can be removed, I've just added it as a prefer it there :)
Jon
30-Mar-2007 06:00
@ PHP-expert 19-Jul-2006 10:30
This should be a little faster:
<?php
function randomkeys($length)
{
$pattern = "1234567890abcdefghijklmnopqrstuvwxyz";
$key = $pattern{rand(0,36)};
for($i=1;$i<$length;$i++)
{
$key .= $pattern{rand(0,36)};
}
return $key;
}
?>
28-Mar-2007 10:05
I don't know how fast this is, but it generates a random number of a certain length. Simply adjust the length variable to your liking.
function makeordernum()
{
$length = 8;
for($i=0;$i<$length;$i++)
{
$number .= rand(0,9);
}
return $number;
}
08-Mar-2007 06:41
#correction of my last post, wrong operator on ($keys < count($returnme)-1) , additional reset arg added for frequent use
Trying to pick up random keys from an array but don't want any duplicates?
try this
<?php
//returns an array of random keys between 2 numbers
function &UniqueRands($min, $max, $keys, $reset=true){
static $returnme = array();
if($reset) $returnme = array();
//while is used to avoid recursive the whole function
while(in_array($x = rand($min,$max),$returnme));
$returnme[] = $x;
//$keys are the number of random integers in the array
//must not be more than the sub of max - min
if($keys > count($returnme) && count($returnme) < ($max-$min))
UniqueRands($min, $max, $keys,false);
return $returnme;
}
//usage
$rands = & UniqueRands(0, 100, 30);
print_r($rands);
//with an array
$vararry = array('red', 'blue', 'green', 'yellow','black');
$rands = & UniqueRands(0, count($vararry)-1, 3);
foreach($rands as $x)
echo "$vararry[$x],";
?>
08-Mar-2007 05:51
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.
07-Mar-2007 04:00
kurtubba's code was helpful, but didn't quite work for me.
Here's my version in case anyone has the same issue:
<?php
function UniqueRands($min, $max, $keys){
static $retval = array();
$x = rand($min,$max);
if(!in_array($x,$retval)){
array_push($retval, $x);
}
if($keys > count($retval)){
UniqueRands($min, $max, $keys);
}
return $retval;
}
$var = UniqueRands(1, 4, 4);
print_r($var);
?>
Bear in mind I'm not the best with php! But my version worked for me at least.
07-Mar-2007 01:40
Trying to pick up random keys from an array but don't want any duplicates?
try this
//returns an array of random keys between 2 numbers
function &UniqueRands($min, $max, $keys){
static $returnme = array();
while(in_array($x = rand($min,$max),$returnme));
$returnme[] = $x;
if($keys < count($returnme)-1 && $keys < ($max-$min))
UniqueRands($min, $max, $keys);
return $returnme;
}
//usage
$rands = & UniqueRands(0, 15, 5);
02-Mar-2007 03:51
Using rand()%x is faster than rand(0,x) yes, but it is wrong.
Consider the following example:
RAND_MAX is 32768 (like on Windows for example)
You use rand()%30000
Imagine rand() returns a value between 30000 and 32768.
Modulo could make any value between 0 and 2768, but not any between 2769 and 29999 (except the value is below 29999).
This would double the chance of getting a number between 0 and 2768, which is speaking against the principles of randomness.
28-Feb-2007 04:06
This function uses rand() to create a random string of specified length from an optionally supplied string of characters. It is good for generating passwords that only consist of alphanumeric characters or codes that must consist of a defined character space such as for barcodes. It can also be used to generate random hexadecimal numbers for things like encryption keys.
It is very fast, and allows for generation of strings of unlimited length.
<?php
function rand_string($len, $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789')
{
$string = '';
for ($i = 0; $i < $len; $i++)
{
$pos = rand(0, strlen($chars)-1);
$string .= $chars{$pos};
}
return $string;
}
?>
22-Feb-2007 11:54
The example from "relsqui at armory dot com" is wrong. It talks about bit operations and uses "&", but is actually an example of using modulus and should use "%". The idea is that "rand()%(x+1)" is faster than "rand(0,x)". I agree, it is. But not a lot.
Here's the fastest function I can think of for making pseudo-unique, valid IDs for HTML tags, in which the first character can't be a number:
function makeID() {
$s="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
return $s{rand()%52}.$s{rand()%62}.(repeat ad libitum).$s{rand()%62};
}
Everyone wants to use so much code to get multiple unique AND at the same time have them also be random values. Here's the smallest code I could think of to do it - no loops necessary:
<?php
// demonstrates how to get any
// number of unique random numbers
// make an array with values 1 through 100
$a=range(1,100);
// randomly order it
shuffle($a);
// pull out the first two values, for example
// they will be random AND non-overlapping
$rand1=$a[0];
$rand2=$a[1];
echo '<pre>';
print_r($rand1);
echo '<br>';
print_r($rand2);
echo '</pre>';
?>
03-Feb-2007 11:02
A single line random string generator.
Since crypt() function generally generates a string of 32 characters that contains some non-alphanumeric characters, my code does not guarantee the length of the random string, but generally speaking, it is efficient up to 24 characters.
substr(preg_replace('/[\/\\\:*?"<>|.$^1]/', '', crypt(time())), 0, 16);
17-Jan-2007 08:24
Generate a random string of size 10 made of upper and lower chars
$str = '';
for ($i=1; $i<=10; $i++){
$set = array(rand (65,90),rand(97,122));
$str .= chr($set[rand(0,1)]);
}
echo $str;
14-Nov-2006 09:32
The problem with these random row functions below is that they require you to fetch all the query results first. Now this may be OK for a small resultset - but in that case why not just use the SQL 'ORDER BY RAND() LIMIT 10' to do the job.
The real problem arises when you want a small random selection from a large query resultset; in that case the SQL RAND() function causes the query to run very slowly. It is then that we need to do the processing in php, and fetching every row from a large query resultset first rather defeats the purpose.
The following is a far simpler and more efficient solution to this problem. It will also cope with queries that do not return distinct rows.
<?php
function randomselection($c, $sql) {
// run the query
$result=mysql_query($sql) or die($sql);
// get the upper limit for rand()
$up = mysql_num_rows($result)-1;
// check that there is more data than rows required
if ($up <= $c) {
while ($row=mysql_fetch_assoc($result)) {
$selection[] = $row;
}
return $selection;
}
// set up array to hold primary keys and elliminate duplicates
// since random DOES NOT mean unique
// or the query may not return DISTINCT rows
$keys = array();
// get random selection
while (count($keys) < $c) {
// get random number for index
$i = rand(0, $up);
// move pointer to that row number and fetch the data
mysql_data_seek($result, $i);
$row = mysql_fetch_assoc($result);
// check if the primary key has already been fetched
if (!in_array($row['id'], $keys)) {
// store the row
$selection[] = $row;
// store the id to prevent duplication
$keys[] = $row['id'];
}
}
return $selection;
}
?>
Fully tested and certified bug-free ;)
31-Oct-2006 03:45
You could try this, it works fine :
<?php
$connection = mysql_connect ($host, $login, $password);
mysql_select_db ($DataBase, $connection) ;
$c = 5 ; // Whatever..
protected function randomselection($c, $connection) {
$data = getdata($connection) ; // Get your datas somewhere you like to
$totalcount = count($data) ;
$j = array() ;
if ($c > $totalcount) { $newdata = $data ; } // if not enough datas rows in $data
else {
for($i = 0; $i <= $c; $i++) {
$exists = 1 ;
for($exists > 0; $exists++;) {
$test = mt_rand(1,$totalcount) ; // depends on where you want to start - can also use rand()
if(!in_array( $test , $j )) { $j[$i] = $test ; $exists = 0 ; }
}
$newdata[$i] = $data[$j[$i]] ;
}
}
return $newdata ;
}
?>
correction from the function below... this works better:
function randomselection($sql, $c) {
$data = getdata($sql);
$totalcount = count($data);
$j = array();
if($totalcount < $c) {//not enough data points
return $data;
}
for($i = 0; $i < $c; $i++) {
$j[$i] = mt_rand(0,$totalcount-1);
$newdata[$i] = $data[$j[$i]];
unset($data[$j[$i]]);
sort($data);
$totalcount--;
}
return $newdata;
}
15-Oct-2006 02:30
Here is a function that selects a random bunch of rows from a database statement. The getdata() function returns a multidimensional array of data (e.g. - just to explain - dont take this literally)
$data[0] = array("ID"=>1, "name", "test row 1");
$data[1] = array("ID"=>2, "name", "test row 2");
function randomselection($sql, $c, $withoutreplacement = 1) {
//$c = count of rows to be selected
$data = getdata($sql);
$totalcount = count($data);
$j = array();
if($totalcount < $c) {//not enough data points
return $data;
}
for($i = 0; $i < $c; $i++) {
$exists = 1
if($withoutreplacement) {
while($exists > 0 && $exists < 100) {
$j[$i] = floor(rand(0,$totalcount-1));
if(!in_array( $j[$i] , $j , 1 )) {
$exists = 0;
}
else {
$exists++;
}
}
}
else {
$j[$i] = floor(rand(0,$totalcount-1));
}
$newdata[$i] = $data[$j[$i]];
}
return $newdata;
}
27-Sep-2006 02:42
frank, nick at nerdynick dot com, and kniht
this is now O(n) instead of O(n^2) ish...
<?php
function rand_permute($size, $min, $max)
{
$retval = array();
//initialize an array of integers from $min to $max
for($i = $min;$i <= $max;$i++)
{
$retval[$i] = $i;
}
//start with the the first index ($min).
//randomly swap this number with any other number in the array.
//this way we guarantee all numbers are permuted in the array,
//and we assure no number is used more than once (technically reiterating prev line).
//therefore we don't have to do the random checking each time we put something into the array.
for($i=$min; $i < $size; $i++)
{
$tmp = $retval[$i];
$retval[$i] = $retval[$tmpkey = rand($min, $max)];
$retval[$tmpkey] = $tmp;
}
return array_slice($retval, 0, $size);
}
?>
24-Jul-2006 04:58
A simple snippet of code that generates a random number with exceptions.
<?php
function numberGen() {
function research() {
echo "Search Over";
$seed = make_seed();
$check = check_num($seed);
}
function make_seed()
{
$seed = rand(0, 10);
return $seed;
}////////////////////////////
function check_num($value) {
$comparison[0] = 0;
$comparison[1] = 1;
$comparison[2] = 2;
$comparison[3] = 3;
$comparison[4] = 4;
$comparison[5] = 5;
$comparison[6] = 6;
$comparison[7] = 8;
$comparison[8] = 9;
$comparison[10] = 10;
if($value != $comparison[5]) {
echo "$value";
} else {
echo "Researching";
research();
}
}////////////////////////////
$seed_start = make_seed();
$check_start = check_num($seed_start);
}
numberGen();
?>
it is much easier
just add $key = ""; before FOR
19-Jul-2006 10:30
Improofed the last function about random strings:
<?php
function randomkeys($length)
{
$pattern = "1234567890abcdefghijklmnopqrstuvwxyz";
for($i=0;$i<$length;$i++)
{
if(isset($key))
$key .= $pattern{rand(0,35)};
else
$key = $pattern{rand(0,35)};
}
return $key;
}
?>
So there isn't anymore an error (notice) about $key when FOREACH runs the first time.
03-Apr-2006 05: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
03-Mar-2006 12: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!
08-Feb-2006 06: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
25-Jan-2006 11: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"));
20-Jan-2006 02:54
@ mozzer:
The only difference ist that your code does not allow codes < 100000. Try
$num = sprintf ('%06d', rand(0, 999999));
18-Jan-2006 09: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";
?>
28-Dec-2005 07: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.
13-Dec-2005 07: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)) );
?>
12-Oct-2005 01: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;
}
08-Oct-2005 03: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
05-Oct-2005 01: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;
}
28-Sep-2005 11: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;
}
?>
18-Sep-2005 05: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.
13-Sep-2005 09: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);
28-Aug-2005 09: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.
28-Aug-2005 07: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.
25-Aug-2005 01: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 ;
13-Jul-2005 07: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));
08-Jul-2005 04: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];
05-Jul-2005 02:04
[quote]SELECT * FROM tablename WHERE id>='$d' LIMIT 1[/quote]
typo: $d should be $id
^^
04-Jul-2005 05: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);
?>
27-Jun-2005 03: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)
21-Jun-2005 04: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
13-Jun-2005 02: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
07-Jun-2005 07: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;
}
}
29-May-2005 06: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);
}
?>
25-May-2005 06: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...
25-May-2005 08: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;
?>
25-May-2005 07: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;
?>
10-May-2005 11: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);
}
04-May-2005 05: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);
}
28-Apr-2005 10: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
21-Apr-2005 09:33
why so complicated?
this works fine for me:
<?php
function randomstring($length) {
$random = rand();
$string = md5($random);
$output = substr($string,$length);
return $output;
}
?>
16-Apr-2005 12: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);
31-Mar-2005 01: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
09-Mar-2005 05: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);
27-Feb-2005 09: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;
}
25-Feb-2005 05: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.
15-Feb-2005 04: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]
<?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
?>
09-Feb-2005 03: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));
?>
08-Feb-2005 09: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 )
03-Feb-2005 12: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;
?>
27-Jan-2005 04: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);
?>
21-Jan-2005 11: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).
29-Dec-2004 03: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");
12-Sep-2004 03: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.
11-Sep-2004 09:45
To easily generate large numbers, or random strings such as passwords, take a look at the below function.
http://aidanlister.com/repos/v/function.str_rand.php
04-Sep-2004 04: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)
08-Dec-2003 10: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.
03-Jun-2003 08: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
30-Oct-2002 01: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