# rand

(PHP 4, PHP 5)

randГенерирует случайное число

### Описание

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

При вызове без параметров `min` и `max`, возвращает псевдослучайное целое в диапазоне от 0 до getrandmax(). Например, если вам нужно случайное число между 5 и 15 (включительно), вызовите rand(5, 15).

Замечание: На некоторых платформах (таких как Windows) getrandmax() всего лишь 32767. Чтобы расширить диапазон, используйте параметры `min` и `max`, или обратитесь к функции mt_rand().

### Список параметров

`min`

Наименьшее значение, которое может быть возвращено (по-умолчанию: 0)

`max`

Наибольшее значение, которое может быть возвращено (по-умолчанию: getrandmax())

### Возвращаемые значения

Псевдослучайное значение в диапазоне от `min` (или 0) до `max` (или getrandmax()).

### Список изменений

Версия Описание
4.2.0Генератор случайных чисел инициализируется автоматически.

### Примеры

Пример #1 Пример использования rand()

``` <?phpecho rand() . "\n";echo rand() . "\n";echo rand(5, 15);?> ```

Результатом выполнения данного примера будет что-то подобное:

```7771
22264
11
```

### Смотрите также

• srand() - Изменяет начальное число генератора псевдослучайных чисел
• getrandmax() - Вовзращает максимально возможное случайное число
• mt_rand() - Генерирует случайное значение методом mt

## Коментарии

``` 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). ```
2005-01-21 04:23:39
http://php5.kiev.ua/manual/ru/function.rand.html
``` 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. <?php 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;      }        } ?> ```
2005-06-07 01:44:33
http://php5.kiev.ua/manual/ru/function.rand.html
``` 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); } ?> ```
2006-09-27 08:42:35
http://php5.kiev.ua/manual/ru/function.rand.html
``` 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 (      => 31      => 0      => 0      => 31      => 0      => 0      => 30      => 0      => 0      => 31      => 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 (      => 8      => 8      => 14      => 16      => 9      => 11      => 8      => 9      => 7      => 7      => 9 ) Much more randomly distributed! Conclusion: mt_rand() is not just faster, it is a far superior algorithm. ```
2007-03-07 22:51:28
http://php5.kiev.ua/manual/ru/function.rand.html
``` 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 ```
2007-04-05 06:42:35
http://php5.kiev.ua/manual/ru/function.rand.html
``` 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. ```
2007-05-23 20:36:22
http://php5.kiev.ua/manual/ru/function.rand.html
``` 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. ```
2007-09-10 09:18:20
http://php5.kiev.ua/manual/ru/function.rand.html
``` 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, ' ')));         \$Max = mysql_result (mysql_query (\$SQL), 0);     \$Random = rand (0, \$Max);         //If the random number is 99, and the database only has 100 rows     //We'll subtract the random number, so we don't exceed 100, thus preventing a MySQL error message     return \$Query . sprintf ('LIMIT %d, %d', (\$Max < \$Rows) ? 0 : ((\$Random > \$Max - \$Rows) ? \$Max - \$Rows : \$Random), \$Rows); } //Instead of using MySQL's RAND(), we use LIMIT to fetch rows //E.g. LIMIT 5,9 fetches from row 5, and the subsequent 9 \$SQL = mysql_rand ('SELECT row FROM table'); //SELECT row FROM table LIMIT x, y ?> or SQL: SELECT * FROM Table T JOIN (SELECT FLOOR(MAX(ID)*RAND()) AS ID FROM Table) AS x ON T.ID >= x.ID LIMIT 1; ```
2008-04-26 15:27:25
http://php5.kiev.ua/manual/ru/function.rand.html
``` quick way to generate randomish numbers and simple strings. no messing around with functions, so you can just pop the line into the middle of your existing code. not the most perfect for sure, but ok for plenty of situations... <?php \$random_number = intval( "0" . rand(1,9) . rand(0,9) . rand(0,9) . rand(0,9) . rand(0,9) ); // random(ish) 5 digit int \$random_string = chr(rand(65,90)) . chr(rand(65,90)) . chr(rand(65,90)) . chr(rand(65,90)) . chr(rand(65,90)); // random(ish) 5 character string ?> hope someone finds it useful for somthing. regards, deeeeeen alxndr0u ```
2008-07-30 19:29:37
http://php5.kiev.ua/manual/ru/function.rand.html
``` Generate a random 5 character alpha string: <?php print preg_replace('/([ ])/e', 'chr(rand(97,122))', '     '); ?> ```
2008-10-20 15:33:21
http://php5.kiev.ua/manual/ru/function.rand.html
``` I also enjoy making one-liners. 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. <?php for (\$s = '', \$i = 0, \$z = strlen(\$a = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789')-1; \$i != 32; \$x = rand(0,\$z), \$s .= \$a{\$x}, \$i++); ?> If you don't want the same character to appear beside itself, use this: <?php for (\$i = 0, \$z = strlen(\$a = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890')-1, \$s = \$a{rand(0,\$z)}, \$i = 1; \$i != 32; \$x = rand(0,\$z), \$s .= \$a{\$x}, \$s = (\$s{\$i} == \$s{\$i-1} ? substr(\$s,0,-1) : \$s), \$i=strlen(\$s)); ?> For those of you who want both as a function, use this: <?php function rand_chars(\$c, \$l, \$u = FALSE) {  if (!\$u) for (\$s = '', \$i = 0, \$z = strlen(\$c)-1; \$i < \$l; \$x = rand(0,\$z), \$s .= \$c{\$x}, \$i++);  else for (\$i = 0, \$z = strlen(\$c)-1, \$s = \$c{rand(0,\$z)}, \$i = 1; \$i != \$l; \$x = rand(0,\$z), \$s .= \$c{\$x}, \$s = (\$s{\$i} == \$s{\$i-1} ? substr(\$s,0,-1) : \$s), \$i=strlen(\$s));  return \$s; } ?> string \$c is the string of characters to use. integer \$l is how long you want the string to be. boolean \$u is whether or not a character can appear beside itself. Examples: rand_chars("ABCEDFG", 10) == GABGFFGCDA rand_chars("ABCEDFG", 10, TRUE) == CBGFAEDFEC ```
2008-12-06 18:00:24
http://php5.kiev.ua/manual/ru/function.rand.html
``` Easy way for mysql: random row the 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); // pick one \$rand = rand(1,\$max); \$lekerdezes2 = mysql_query("select * from table limit \$rand, 1"); // that's all folks :) ?> ```
2009-03-04 02:16:57
http://php5.kiev.ua/manual/ru/function.rand.html
``` 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. ```
2009-03-15 10:56:47
http://php5.kiev.ua/manual/ru/function.rand.html
``` A nice function to generate a random string, using any character: <?php function generateRandStr(\$length){       \$randstr = "";       for(\$i=0; \$i<\$length; \$i++){          \$randnum = mt_rand(0,61);          if(\$randnum < 10){             \$randstr .= chr(\$randnum+48);          }else if(\$randnum < 36){             \$randstr .= chr(\$randnum+55);          }else{             \$randstr .= chr(\$randnum+61);          }       }       return \$randstr;    } ?> Simply use: generateRandStr(10); Sample output: \$%29zon(4f ```
2009-04-25 13:13:39
http://php5.kiev.ua/manual/ru/function.rand.html
``` Improved random string generation function: <?php // Generate a random character string function rand_str(\$length = 32, \$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890') {     // Length of character list     \$chars_length = (strlen(\$chars) - 1);     // Start our string     \$string = \$chars{rand(0, \$chars_length)};         // Generate random string     for (\$i = 1; \$i < \$length; \$i = strlen(\$string))     {         // Grab a random character from our list         \$r = \$chars{rand(0, \$chars_length)};                 // Make sure the same two characters don't appear next to each other         if (\$r != \$string{\$i - 1}) \$string .=  \$r;     }         // Return the string     return \$string; } ?> ```
2009-05-08 18:23:09
http://php5.kiev.ua/manual/ru/function.rand.html
``` To Jano and Peta: Thanks for the code. In real world usage, I only had one problem with it: It will never return the first result of the array (or it will return nothing if there's only one item in the array). To remedy this, I simply subtracted 1 from  <?php \$rand = rand(1,\$max); ?> like so: <?php \$rand = rand(1,\$max)-1; ?> Thanks though, for the code you supplied. It was exactly what I needed. ```
2009-05-26 21:21:37
http://php5.kiev.ua/manual/ru/function.rand.html
``` I thought this function (random color) might be of use to someone [to create and return a random hex for HTML colors]: <?php function get_random_color() {     for (\$i = 0; \$i<6; \$i++)     {         \$c .=  dechex(rand(0,15));     }     return "#\$c"; } ?> ```
2009-06-15 19:49:54
http://php5.kiev.ua/manual/ru/function.rand.html
``` Here's a simple function to generate a random date between a start date and an end date.  It is inclusive of BOTH dates - so using dates 2009-04-01 and 2009-04-03 would generate a random date that could be 2009-04-01, 2009-04-02 or 2009-04-03. It won't work if the end date is prior to the start date and if you use a non-existant date (eg 2009-02-30) it defaults to 1970-01-01 the longer version: <?php function makeRandomDateInclusive(\$startDate,\$endDate){     \$days = round((strtotime(\$endDate) - strtotime(\$startDate)) / (60 * 60 * 24));     \$n = rand(0,\$days);     return date("Y-m-d",strtotime("\$startDate + \$n days"));    } ?> and the one-line version for compactness freaks: <?php function makeRandomDateInclusive(\$startDate,\$endDate){        return date("Y-m-d",strtotime("\$startDate + ".rand(0,round((strtotime(\$endDate) - strtotime(\$startDate)) / (60 * 60 * 24)))." days")); } ?> it is called like this  <?php echo makeRandomDateInclusive('2009-04-01','2009-04-03'); ?> Hope this is of some use to someone ```
2009-07-29 10:52:09
http://php5.kiev.ua/manual/ru/function.rand.html
``` Another way to create an array of random numbers where there are no identical numbers. (\$n = number of random numbers to return in the array \$min = minimum number \$max = maximum number) <?php  function uniqueRand(\$n, \$min = 0, \$max = null)  {   if(\$max === null)    \$max = getrandmax();   \$array = range(\$min, \$max);   \$return = array();   \$keys = array_rand(\$array, \$n);   foreach(\$keys as \$key)    \$return[] = \$array[\$key];   return \$return;  } ?> ```
2010-01-02 13:24:34
http://php5.kiev.ua/manual/ru/function.rand.html
``` Generate a random 5 character A-Z0-9  string <?php for (\$i=0; \$i<6; \$i++) {      \$d=rand(1,30)%2;      echo \$d ? chr(rand(65,90)) : chr(rand(48,57));  } ?> # php -r 'for (\$i=0; \$i<6; \$i++) { \$d=rand(1,30)%2; echo \$d ? chr(rand(65,90)) : chr(rand(48,57)); } echo "\n";' 14BW1A ```
2010-03-05 20:41:06
http://php5.kiev.ua/manual/ru/function.rand.html
``` <?php //To Pull 7 Unique Random Values Out Of AlphaNumeric //removed number 0, capital o, number 1 and small L //Total: keys = 32, elements = 33 \$characters = array( "A","B","C","D","E","F","G","H","J","K","L","M", "N","P","Q","R","S","T","U","V","W","X","Y","Z", "1","2","3","4","5","6","7","8","9"); //make an "empty container" or array for our keys \$keys = array(); //first count of \$keys is empty so "1", remaining count is 1-6 = total 7 times while(count(\$keys) < 7) {     //"0" because we use this to FIND ARRAY KEYS which has a 0 value     //"-1" because were only concerned of number of keys which is 32 not 33     //count(\$characters) = 33     \$x = mt_rand(0, count(\$characters)-1);     if(!in_array(\$x, \$keys)) {        \$keys[] = \$x;     } } foreach(\$keys as \$key){    \$random_chars .= \$characters[\$key]; } echo \$random_chars; ?> ```
2010-05-31 23:16:50
http://php5.kiev.ua/manual/ru/function.rand.html
``` Random integers with normal distribution,  it's not scientifically approved, but worked for me. <?php /* * @param float  \$mean, desired average * @param number \$sd, number of items in array * @param number \$min, minimum desired random number * @param number \$max, maximum desired random number * @return array */ function array_distribute(\$mean,\$sd,\$min,\$max){     \$result = array();     \$total_mean = intval(\$mean*\$sd);     while(\$sd>1){         \$allowed_max = \$total_mean - \$sd - \$min;         \$allowed_min = intval(\$total_mean/\$sd);         \$random = mt_rand(max(\$min,\$allowed_min),min(\$max,\$allowed_max));         \$result[]=\$random;         \$sd--;         \$total_mean-=\$random;     }     \$result[] = \$total_mean;     return \$result; } ?> ```
2010-09-10 17:18:24
http://php5.kiev.ua/manual/ru/function.rand.html
``` Much easier way to generate random string of numbers and letters: <?php \$n = rand(10e16, 10e20); echo base_convert(\$n, 10, 36); ?> This generates strings of about 11 characters. Experiment with the range for rand() if you want shorter or longer. ```
2011-02-24 13:26:20
http://php5.kiev.ua/manual/ru/function.rand.html
``` Random is NOT actually random. It is easily illustrated by multiplying rand(1,500) by rand(1,500) and showing the output on the image: <?php header("Content-type: image/png"); \$img = imagecreatetruecolor(500,500); \$ink = imagecolorallocate(\$img,255,255,255); for(\$i=0;\$i<500;\$i++) {   for(\$j=0;\$j<500;\$j++) {   imagesetpixel(\$img, rand(1,500), rand(1,500), \$ink1);   } } imagepng(\$img); imagedestroy(\$img); ?> I expected to get pixel noise, but instead one can see plain diagonal lines. ```
2011-03-19 15:41:32
http://php5.kiev.ua/manual/ru/function.rand.html
``` Another one-liner to generate strings: <?php substr(str_shuffle(str_repeat('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789',5)),0,5); ?> The strings can be repeated to have the possibility that a character appears multiple times. ```
2011-08-02 10:32:58
http://php5.kiev.ua/manual/ru/function.rand.html
``` I couldn't find a suitable random alpha-numeric generator function so I rolled my own. It gives a random number in base 36 (0-9, a-z) to a given length. <?php function randomAlphaNum(\$length){     \$rangeMin = pow(36, \$length-1); //smallest number to give length digits in base 36     \$rangeMax = pow(36, \$length)-1; //largest number to give length digits in base 36     \$base10Rand = mt_rand(\$rangeMin, \$rangeMax); //get the random number     \$newRand = base_convert(\$base10Rand, 10, 36); //convert it         return \$newRand; //spit it out } ?> hopefully helps someone ```
2011-10-01 23:34:02
http://php5.kiev.ua/manual/ru/function.rand.html
``` I had to create a function that generates a random binominal distributed integer. Take a look at the following Wiki article: http://en.wikipedia.org/wiki/Binomial_distribution Here is my solution: <?php function bin_rand(\$min = null, \$max = null) {     \$min = (\$min) ? (int) \$min : 0;     \$max = (\$max) ? (int) \$max : PHP_INT_MAX;         \$range = range(\$min, \$max);     \$average = array_sum(\$range) / count(\$range);         \$dist = array();     for (\$x = \$min; \$x <= \$max; \$x++) {         \$dist[\$x] = -abs(\$average - \$x) + \$average + 1;     }         \$map = array();     foreach (\$dist as \$int => \$quantity) {         for (\$x = 0; \$x < \$quantity; \$x++) {             \$map[] = \$int;         }     }         shuffle(\$map);     return current(\$map); } ?> ```
2012-02-28 17:44:51
http://php5.kiev.ua/manual/ru/function.rand.html
``` 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 ```
2012-03-28 16:43:23
http://php5.kiev.ua/manual/ru/function.rand.html
``` 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) ```
2012-07-24 12:01:16
http://php5.kiev.ua/manual/ru/function.rand.html
``` 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. Given the numbers 13050,  4267,  25352, construct the equations 4267 = (13050a+c) % 32768 25352 = (4267a+c) % 32768 Solving for a and c gives a = 20077 c = 12345 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. ```
2013-01-30 00:51:15
http://php5.kiev.ua/manual/ru/function.rand.html
``` If you are looking for generate a random expression, like password with alphanumeric or any other character, use this function: <?php function GeraHash(\$qtd){ //Under the string \$Caracteres you write all the characters you want to be used to randomly generate the code. \$Caracteres = 'ABCDEFGHIJKLMOPQRSTUVXWYZ0123456789'; \$QuantidadeCaracteres = strlen(\$Caracteres); \$QuantidadeCaracteres--; \$Hash=NULL;     for(\$x=1;\$x<=\$qtd;\$x++){         \$Posicao = rand(0,\$QuantidadeCaracteres);         \$Hash .= substr(\$Caracteres,\$Posicao,1);     } return \$Hash; } //Here you specify how many characters the returning string must have echo GeraHash(30); ?> ```
2013-02-01 19:40:11
http://php5.kiev.ua/manual/ru/function.rand.html
``` 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! <?php srand(file_get_contents('http://seed.feeds.labs.coop'));  ?> ```
2013-10-05 22:41:03
http://php5.kiev.ua/manual/ru/function.rand.html
``` I agree with Sebmil (function.array-rand#105265) that "array_rand()" produces weird and very uneven random distribution (as of my local PHP 5.3.8 and my public host's PHP 5.2.17). Unfortunately, I haven't got any access either to a server with the latest PHP version. My info is for those of you who like to check things for themselves and who don't believe all of the official statements in the docs. I've made a simple adjustment of his test code like this: <?php  \$s=1;    // Start value \$c=50;    // Count / End value \$test=array_fill(\$s, \$c, 0); \$ts=microtime(true); for(\$i=0; \$i<5000000; \$i++){     \$idx=mt_rand(\$s, \$c);    // Try it with rand() - simpler but more evenly distributed than mt_rand()     \$test[\$idx]++; } \$te=microtime(true); \$te=(\$te-\$ts)*1000.0;    // Loop time in miliseconds asort(\$test); echo "Test mt_rand() in ".\$te." ms: <br/>\n"; foreach(\$test as \$k=>\$v) echo "\$k :\t\$v <br/>\n"; ?> And it appears to me that simple "\$idx=rand(0, count(\$test)-1);" is much better than "\$idx=array_rand(\$test, 1);". And what's more the simpler and a bit slower (0 ms up to total 712.357 ms at 5 mln cycles) "rand()" is better than "mt_rand()" in simple everyday use cases because it is more evenly distributed (difference least vs. most often numbers: ca. 0.20-1.28 % for "rand()" vs. ca. 1.43-1.68 % for "mt_rand()"). Try it for yourself... although it depends on your software and hardware configuration, range of numbers to choose from (due to random patterns), number of cycles in the loop, and temporary (public) server load as well. ```
2015-04-16 14:51:54
http://php5.kiev.ua/manual/ru/function.rand.html
``` From PHP 7.1 rand() is documented as an alias of mt_rand(). Actually, if they are called with two arguments where the second is smaller than the first, their output differs. For example var_dump(rand(2,1), mt_rand(2,1)); may return Warning: mt_rand(): max(1) is smaller than min(2) int(2) bool(false) where rand() will return a random value between \$max and \$min ```
2017-03-10 16:15:46
http://php5.kiev.ua/manual/ru/function.rand.html
``` I wrote this many years back and just found it. thought I share. what it does is generate either random numbers 0-9, Alphabets A-Z or Alphanumeric which is a combination of numbers and alphabets. I turned it into a class before sharing. do with it what you please. Solved some of my problems.  <?php class Random{   public static function Numeric(\$length)       {           \$chars = "1234567890";           \$clen   = strlen( \$chars )-1;           \$id  = '';           for (\$i = 0; \$i < \$length; \$i++) {                   \$id .= \$chars[mt_rand(0,\$clen)];           }           return (\$id);       }   public static function Alphabets(\$length)       {           \$chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";           \$clen   = strlen( \$chars )-1;           \$id  = '';           for (\$i = 0; \$i < \$length; \$i++) {                   \$id .= \$chars[mt_rand(0,\$clen)];           }           return (\$id);       }   public static function AlphaNumeric(\$length)       {           \$chars = "1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";           \$clen   = strlen( \$chars )-1;           \$id  = '';           for (\$i = 0; \$i < \$length; \$i++) {                   \$id .= \$chars[mt_rand(0,\$clen)];           }           return (\$id);       } }   echo Random::Numeric(6); # eg result: "567268"   echo Random::Alphabets(9); # eg result: IAGRmZyJS   echo Random::AlphaNumeric(10); #eg result: Gzt6syUS8M ?> ```
2017-08-17 01:49:57
http://php5.kiev.ua/manual/ru/function.rand.html
``` well , this is my vision about "custom random string" : <?php function s(\$length){   for(\$i=0;(\$i<\$length)and((\$what=rand(1,3))and( ((\$what==1)and(\$t=rand(48,57) ))or ((\$what==2)and (\$t=rand(65,90))) or ((\$what==3)and (\$t=rand(97,122)))  ) and  (print chr(\$t)));\$i++); } s(10); ?> ```
2018-10-20 17:30:18
http://php5.kiev.ua/manual/ru/function.rand.html

Поддержать сайт на родительском проекте КГБ