In regards to mno2go's note below on randomly generated strings, I am not sure what's inefficient about this. I like it and am using it in several modules (so thanks). I made a few tweaks though. There is a fence-post error in the code (a string's range is 0 to n-1). There is also excessive calls to strlen.
<?php
function generateCode($length=6) {
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPRQSTUVWXYZ0123456789";
$code = "";
$clen = strlen($chars) - 1; //a variable with the fixed length of chars correct for the fence post issue
while (strlen($code) < $length) {
$code .= $chars[mt_rand(0,$clen)]; //mt_rand's range is inclusive - this is why we need 0 to n-1
}
return $code;
}
?>
rand
(PHP 4, PHP 5)
rand — 乱数を生成する
説明
int rand ( [int $min, int $max] )オプションの引数 min,max を省略してコールした場合、rand() は 0 と RAND_MAX の間の擬似乱数(整数)を返します。 例えば、5 から 15 まで(両端を含む)の乱数を得たい場合、 rand(5,15) とします。
注意: (Windows のような)いくつかのプラットフォームでは、RAND_MAX は 32768 と小さな値となっています。 32768 より広い範囲にしたい場合、 min および max を指定することで、 RAND_MAX より大きな範囲の乱数を生成することができます。 もしくは、 mt_rand() をかわりに使用してみてください。
注意: PHP 4.2.0 以降、 srand() または mt_srand() によりランダム数生成器にシードを与える必要はありません。 これは、この処理が自動的に行われるためです。
パラメータ
- min
返す値の最小値 (デフォルトは 0)。
- max
返す値の最大値 (デフォルトは RAND_MAX)。
返り値
min (あるいは 0) から max (あるいは RAND_MAX、それぞれ端点を含む) までの間の疑似乱数値を返します。
変更履歴
| バージョン | 説明 |
|---|---|
| 3.0.7 以降 | 3.0.7 より前のバージョンでは、max の意味は range でした。これらのバージョンにおいて 同じ結果を得るために簡単な例を示すと、 5 から 15 までの乱数を得たい場合には rand (5, 11) とする必要があります。 |
例
例 1112. rand() の例
<?php
echo rand() . "\n";
echo rand() . "\n";
echo rand(5, 15);
?>
上の例の出力は、たとえば 以下のようになります。
7771
22264
11
参考
| srand() |
| getrandmax() |
| mt_rand() |
rand
jfkallen at hotmail dot com
18-Aug-2007 11:21
18-Aug-2007 11:21
alishahnovin at hotmail dot com
14-Aug-2007 02:39
14-Aug-2007 02:39
Quick function that returns an array of unequal random numbers. Works well if you need to assign random values, but want them to all be unique.
<?php
function randiff($min, $max, $num) {
if ($min<$max && $max-$min+1 >= $num && $num>0) {
$random_nums = array();
$i=0;
while($i<$num) {
$rand_num = rand($min, $max);
if (!in_array($rand_num, $random_nums)) {
$random_nums[] = $rand_num;
$i++;
}
}
return $random_nums;
} else {
return false;
}
}
?>
So rather than:
<?php
$var1 = rand(0,10);
$var2 = rand(0,10);
?>
Which could potentially give you two of the same values, you can use:
<?php
$nums = randiff(0,10,2);
$var1 = $nums[0];
$var2 = $nums[1];
?>
mno2go at gmail dot com
04-Aug-2007 06:30
04-Aug-2007 06:30
Perhaps not the most efficient way, but one that is quite simple and provides for easy control over characters used in the generated strings/passwords:
<?php
function generateCode($length=6) {
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPRQSTUVWXYZ0123456789";
$code = "";
while (strlen($code) < $length) {
$code .= $chars[mt_rand(0,strlen($chars))];
}
return $code;
}
?>
rok dot kralj at gmail dot com
16-Jun-2007 04:43
16-Jun-2007 04:43
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)));
}
?>
bozo_z_clown at yahoo dot com
24-May-2007 09:36
24-May-2007 09: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.
blackened at live dot com
30-Apr-2007 12:24
30-Apr-2007 12: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);
}
?>
DKDiveDude at Subima dot com
28-Apr-2007 12:44
28-Apr-2007 12: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>';
}
?>
dxillusion at gmail dot com
13-Apr-2007 02:50
13-Apr-2007 02: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
cjaube at yahoo dot com
07-Apr-2007 01:28
07-Apr-2007 01: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;
}
?>
jont at live dot co dot uk
05-Apr-2007 07:42
05-Apr-2007 07: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
anne[dot]multimedia_at_gmail.com
31-Mar-2007 01:00
31-Mar-2007 01: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;
}
?>
davet15 at hotmail dot com
29-Mar-2007 05:05
29-Mar-2007 05: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;
}
kurtubba at gmail dot com
08-Mar-2007 02:41
08-Mar-2007 02: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],";
?>
phpdev at dunnbypaul dot net
08-Mar-2007 01:51
08-Mar-2007 01: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.
palmnet at gmail dot com
08-Mar-2007 12:00
08-Mar-2007 12: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.
kurtubba at gmail dot com
07-Mar-2007 09:40
07-Mar-2007 09: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);
Patrick Daryll G.
02-Mar-2007 11:51
02-Mar-2007 11: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.
www.mrnaz.com
01-Mar-2007 12:06
01-Mar-2007 12: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;
}
?>
Niels
23-Feb-2007 07:54
23-Feb-2007 07: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};
}
20-Feb-2007 03:59
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>';
?>
tahir at sandikkaya dot name dot tr
04-Feb-2007 07:02
04-Feb-2007 07: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);
jd
18-Jan-2007 04:24
18-Jan-2007 04: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;
dsoussan at gmail dot com
14-Nov-2006 05:32
14-Nov-2006 05: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 ;)
euan_m at yahoo dot fr
31-Oct-2006 11:45
31-Oct-2006 11: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 ;
}
?>
15-Oct-2006 04:24
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;
}
php at ngaru dot com
15-Oct-2006 09:30
15-Oct-2006 09: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;
}
ludicruz at yahoo dot com
27-Sep-2006 09:42
27-Sep-2006 09: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);
}
?>
axe at (opposite of old) dot co za
24-Jul-2006 11:58
24-Jul-2006 11: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();
?>
24-Jul-2006 09:38
it is much easier
just add $key = ""; before FOR
PHP-expert
19-Jul-2006 05:30
19-Jul-2006 05: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.
thebomb-hq [AT] gmx [DOT] de
04-Apr-2006 12:48
04-Apr-2006 12: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 08:01
03-Mar-2006 08: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 02:50
09-Feb-2006 02: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 07:48
25-Jan-2006 07: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 10:54
20-Jan-2006 10: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 05:35
19-Jan-2006 05: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 03:49
29-Dec-2005 03: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 03:40
14-Dec-2005 03: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 08:25
12-Oct-2005 08: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 10:50
08-Oct-2005 10: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 08:40
05-Oct-2005 08: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 06:53
28-Sep-2005 06: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 12:58
18-Sep-2005 12: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 04:21
14-Sep-2005 04: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 04:12
29-Aug-2005 04: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 02:15
29-Aug-2005 02: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 08:27
25-Aug-2005 08: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 02:00
14-Jul-2005 02: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 11:14
08-Jul-2005 11: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 09:04
05-Jul-2005 09:04
[quote]SELECT * FROM tablename WHERE id>='$d' LIMIT 1[/quote]
typo: $d should be $id
^^
Corry Gellatly ncl.ac.uk
05-Jul-2005 12:17
05-Jul-2005 12: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 10:28
27-Jun-2005 10: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 11:39
21-Jun-2005 11: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 09:32
13-Jun-2005 09: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 02:44
07-Jun-2005 02: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 01:47
29-May-2005 01: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 01:23
26-May-2005 01: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 03:00
25-May-2005 03: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 02:57
25-May-2005 02: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 06:30
11-May-2005 06: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
05-May-2005 12:57
05-May-2005 12: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 05:29
28-Apr-2005 05: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 04:33
22-Apr-2005 04: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 07:53
16-Apr-2005 07: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 08:19
31-Mar-2005 08: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 01:55
10-Mar-2005 01: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 05:19
28-Feb-2005 05: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 01:03
25-Feb-2005 01: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
16-Feb-2005 12:29
16-Feb-2005 12: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 03: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 11:47
09-Feb-2005 11: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 05:50
09-Feb-2005 05: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 08:10
03-Feb-2005 08: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 12:32
27-Jan-2005 12: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 07:23
21-Jan-2005 07: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 11:03
29-Dec-2004 11: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 10:58
12-Sep-2004 10: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 04:45
11-Sep-2004 04: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
a_kunyszSPAM at SUXyahoo dot com
04-Sep-2004 11:44
04-Sep-2004 11: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 06:14
09-Dec-2003 06: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 03:40
04-Jun-2003 03: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 09:35
30-Oct-2002 09: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