frank, nick at nerdynick dot com, and knihtthis is now O(n) instead of O(n^2) ish...

<?phpfunction rand_permute($size, $min, $max){$retval = array();//initialize an array of integers from $min to $maxfor($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);}?>

Here's a non-regular expression approach. It generates a random 32 character string consisting of, by default, only A-Z, a-z, and 0-9, but you can change the value of $a for other characters. The random string will be in variable $s after this line.

Since many people (myself included) come to this page looking for a way to do a random string, I present a way that uses arrays and shuffle() instead of rand(). This also has the effect of not repeating any characters in the value set.

$arr = str_split('ABCDEFGHIJKLMNOP'); // get all the characters into an array shuffle($arr); // randomize the array $arr = array_slice($arr, 0, 6); // get the first six (random) characters out $str = implode('', $arr); // smush them back into a string

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.

Another one-liner to generate strings:<?phpsubstr(str_shuffle(str_repeat('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789',5)),0,5);?>The strings can be repeated to have the possibility that a character appears multiple times.

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.

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 :)

The Windows rand() function is quite a lot worse than merely having a low maximum value. It's an ordinary Linear Congruential Generator, which means you only need three consecutive values to be able to predict its entire future output.

Which means the next number that should be spat out is (25352×20077+12345) % 32768 = 19105 -- which indeed it is.

It's not the small rand_max that breaks the algorithm, it's a weakness in the LCG algorithm itself. It's designed for when you only want a few kinda-random numbers occasionally, not if you want to generate any random-looking data.

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.

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

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

like so:

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

Thanks though, for the code you supplied. It was exactly what I needed.

If you are looking for generate a random expression, like password with alphanumeric or any other character, use this function:

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

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).

Something we discovered in Sydney running BBS Systems before the net advent was here, if we didn't seed of another BBS we would going in circles in our System Physicality Abstraction Layers.. The important thing is to seed from a remote system and easy way at the Centroidal Plexus of the web (Chronolabs Cooperative) we offer a seed feed and the following code will randomise you out of the number cycle:

See in PHP both the letters and numbers are seedable as letters are treated as numbers as well. You can always use individual tokens by extracting the Element with DOM.. But below is equally effective!

As an further optimization on janoserki[at]gmail[dot]com previous post i would recommend that you optimize you first part of php/sql code to something like this.

<?php// estimate the number of rows in a table$lekerdezes = mysql_query("select count(*) as rows from table");while ($row = mysql_fetch_assoc($lekerdezes)){$max = $row["rows"];}?>the count(*) is much faster for the database than grabbing the hole dataset from the table.

emad_ramahi at hotmail dot com:I've actually noticed that with a large dataset (100k rows), the query dramatically slows down the server and performance is way too bad.

The way I see it, you have to workable solutions:

Using PHP:

<?php//$Table holds the name of the table we're getting the random row from//$Rows specifies how many rows we need to fetch function mysql_rand ($Query, $Rows = 1) {//getting the table name from $query //what you can do, is replace the $query argument with $table, //this way to dont have to search for the table's name$SQL = sprintf ('SELECT COUNT(*) FROM %s', substr ($query, stripos ($query, 'from')+5, strpos ($query, ' ')));

Easy way for mysql: random rowthe original form is: "... order by rand()"but this is not the best way, because it's very slow by a big database (it can take more minutes to complete the request!)My suggestion:

<?php// estimate the number of rows in a table$lekerdezes = mysql_query("select * from table");$max = mysql_num_rows($lekerdezes);

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

In Suhosin version 0.9.26 (released 2008.08.22) and above:- rand() and srand() are transparently modified to use the Mersenne Twister algorithm with separate state- rand() and mt_rand() have better internal seeding- srand() and mt_srand() are ignored (can be configured)