|
rand
Generate a random integer
(PHP 4, PHP 5)
Example 1158. rand() example<?php The above example will output something similar to: 7771 Related Examples ( Source code ) » rand Examples ( Source code ) » md5 and uniqid Examples ( Source code ) » rand demo Examples ( Source code ) » mt_rand with no arguments Examples ( Source code ) » mt_rand with two arguments Examples ( Source code ) » Create two child classes Examples ( Source code ) » Break statement Examples ( Source code ) » Break in Nested Loops Examples ( Source code ) » Postfix and Prefix Operators summary table Examples ( Source code ) » array_rand Pick one or more random entries out of an array Examples ( Source code ) » Overriding the Function of a Base Class Examples ( Source code ) » Calling an Overridden Function Examples ( Source code ) » Creating a simple line graph - ImagickDraw Examples ( Source code ) » Animated Talking Captcha php class Examples ( Source code ) » Flash video example using very simple .flv Examples ( Source code ) » Png2swf Adding a png Image to a movie using ming Code Examples / Notes » randruku
[quote]SELECT * FROM tablename WHERE id>='$d' LIMIT 1[/quote] typo: $d should be $id ^^ a_kunyszspam
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) euan_m
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 ; } ?> jawsper
why so complicated? this works fine for me: <?php function randomstring($length) { $random = rand(); $string = md5($random); $output = substr($string,$length); return $output; } ?> polmme
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; ?> thebomb-hq
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)," "; echo randomkeys(16)," "; echo randomkeys(32)," "; echo randomkeys(64)," "; ?> output: n94bv1h7 y9qi1qu2us3wged2 00dhax4x68028q96yyoypizjb2frgttp 478d4ab0ikapaiv0hk9838qd076q1yf46nh0ysigds6ob2xtl61odq2nx8dx7t2b patrick daryll g.
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. cjaube
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; } ?> roger
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) kurtubba
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); hoffa
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 viking coder
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); jbarbero
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. emailfire
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 aidan
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 phpdeveloper
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] www.mrnaz.com
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; } ?> ioann dot tschaikowsky
This function generates unique random integers between $min and $max, resets history when new limits are requested or when there are no more numbers to return, never ever hangs or fails, never ever eats more memory than expected. This solution uses static variables in a function, stores previous limits and when those are changed or possible results are exhausted, generates a new list of possible results, then shuffles it and pops one number for each consequent call. PROS: Runs as fast as light when extracting a number, first call time with new limits depends on range size (don't know internal complexity of shuffle()). CONS: Might be quite slow initially with a big range, so probably it is best suited for little ones, and uses static variables so somebody could say "bleah"... but i just can't think a cleaner way to get this done. <?php function unirand($min, $max) { static $s_min = -1; static $s_max = -1; static $s_nums = array(); // if we have new limits if($s_min != $min || $s_max != $max || !count($s_nums)) { // init limits $s_min = $min; $s_max = $max; // create extractions $s_nums = range($s_min, $s_max); shuffle($s_nums); } // return next number return array_pop($s_nums); } ?> snecx
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; ?> gavin
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); } dsoussan
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 ;) snecx
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; ?> niels
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}; } andy
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. kniht
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; } ?> frank
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; } umpalump
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 ferconstantino
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; } rok dot kralj
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))); } ?> sam fullman
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); alishahnovin
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
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; } ?> janus - palacecommunity dot com
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"); anonymous
Note, the function used by PHP to constrain a random number between (min, max) is the following: $number = $min + (($max - $min + 1) * ($number / ($rand_max + 1)); where the following: $number - the initially generated random number $min - the minimum in the range $max - the maximum in the range $rand_max - the maximum possible random value What this algorithm does is constrain the generated number to a 0-1 range, then multiply it against your range, mapping the two to each other. In practice you'll see the following results: For a generated $number of 16384 and a $rand_max of 32768: rand(0, 10) = 5 rand(0, 100) = 50 rand(0, 1000) = 500 with the additional property that if the range you're asking for is larger than $rand_max, random numbers will be in a multiple of $max/$rand_max. bozo_z_clown
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.
andy
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. cmol
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... smaaps
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; } } palmnet
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. pitilezard
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; } cezden
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 24-jul-2006 01:38
it is much easier just add $key = ""; before FOR jont
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 ewspencer
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 mozzer
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"; ?> jfkallen
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; } ?> luis
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); } php-expert
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. tech_niek
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 ) uoseth
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); } ?> corry gellatly ncl.ac.uk
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 \n"; } } $start = 1; $end = 1000; $rangemin = 1; $rangemax = 20000; rand_array($start, $end, $rangemin, $rangemax); ?> dkdivedude
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 ' '; } ?> richardbronosky 1st
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! mark
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]; corry gellatly ncl.ac.uk
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)); richardbronosky 1st
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)) ); ?> jon
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 davet15
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; } pierre c.
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 ; jeswanth
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. horroradore
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. phpdev
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. php
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; } nick
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. expertphp
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 jd
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; ludicruz
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); } ?> goochivasquez -at- gmail
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); 19-feb-2007 06: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 ' '; print_r($rand2); echo '</pre>'; ?> relsqui
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). blackened
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); } ?> 15-oct-2006 08: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 dot net
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)); ?> igge
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 •alien•
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")); dxillusion
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 webdude
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); ?> ishtar
A small comment on phpdev-dunnbypauls conclusion that rand() only generates numbers that are a multiply of 3. <?php $n = rand(0,100000); // with MAX_RAND=32768 ?> Since, 100000/32768=3.05 you get multiples of 3. The random integer will be multiplied by 3.05 to fit between 0 and 100000. rand() works fine, if you don't ask for bigger numbers then RAND_MAX. tahir
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); axe
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(); ?> anne dot multimedia_at_gmail.com
@ 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; } ?> a dot tietje
@ mozzer: The only difference ist that your code does not allow codes < 100000. Try $num = sprintf ('%06d', rand(0, 999999)); 12-feb-2005 06: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 ?> onno
>>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. kurtubba
#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],"; ?> |