Rand

(PHP 4, PHP 5, PHP 7, PHP 8)

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

Описание

rand(int $min, int $max): int

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

Данная функция не генерирует криптографически безопасные значения и не должна использоваться в криптографических целях. Если вам требуется криптографически безопасное значение, подумайте об использовании функций random_int(),
random_bytes() или openssl_random_pseudo_bytes() вместо данной.

Замечание:

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

Замечание: Начиная с PHP 7. 0, rand() использует тот же
алгоритм получения случайных чисел, что и mt_rand(). Для
сохранения обратной совместимости, функция rand() позволяет
задавать параметр max меньше, чем параметр
min. Функция mt_rand() в такой
ситуации будет возвращать false

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

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

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

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

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

Примеры

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

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

Диапазон min — max не должен
выходить за границы getrandmax(). То есть
(max —
min) <= getrandmax(). В противном случае, rand() может возвращать
менее качественные случайные числа.

  • srand() — Изменяет начальное число генератора псевдослучайных чисел
  • getrandmax() — Возвращает максимально возможное случайное число
  • mt_rand() — Генерирует случайное значение методом с помощью генератора простых чисел на базе Вихря Мерсенна
  • random_int() — Генерирует криптографически безопасные псевдослучайные целые числа
  • random_bytes() — Генерирует криптографически безопасные псевдослучайные байты
  • openssl_random_pseudo_bytes() — Генерирует псевдослучайную последовательность байт

whatchildisthis at gmail dot com ¶

13 years ago

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.

Examples:
rand_chars(«ABCEDFG», 10) == GABGFFGCDA
rand_chars(«ABCEDFG», 10, TRUE) == CBGFAEDFEC

relsqui at armory dot com ¶

17 years ago

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,

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

petabyte. se ¶

Alireza Eliaderani ¶

12 years ago

Random integers with normal distribution,
it’s not scientifically approved, but worked for me.

Justin Richer ¶

10 years ago

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

jont at live dot co dot uk ¶

15 years ago

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.

and if you don’t want it the md5 can be removed, I’ve just added it as a prefer it there 🙂

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:

A small comment on phpdev-dunnbypauls conclusion that rand() only generates numbers that are a multiply of 3. 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.

phpdev at dunnbypaul dot net ¶

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.

Much more randomly distributed!

Conclusion: mt_rand() is not just faster, it is a far superior algorithm.

shiawase at gmail dot com ¶

11 years ago

Another one-liner to generate strings:The strings can be repeated to have the possibility that a character appears multiple times.

Improved random string generation function:

matheus at matheusloureiro dot com ¶

9 years ago

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

//Here you specify how many characters the returning string must have

abdufarag at yahoo dot com ¶

1 year ago

I have made this example to generate random number with specific length (10).

razvan_bc at yahoo dot com ¶

this is my vision about «custom random string» :

Hayley Watson ¶

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 equations4267 = (13050a+c) % 3276825352 = (4267a+c) % 32768

Solving for a and c gives

a = 20077c = 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.

Hugo Scott hrmscott at hotmail dot com ¶

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.

Generate a random 5 character alpha string:

bozo_z_clown at yahoo dot com ¶

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.

pasafama at gmail dot com ¶

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.

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

14 years ago

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.

// random(ish) 5 digit int// random(ish) 5 character stringhope someone finds it useful for somthing.

John Galt ¶

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)

thibault dot debatty at gmail dot com ¶

In Suhosin version 0. 26 (released 2008. 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)

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:

ludicruz at yahoo dot com ¶

16 years ago

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

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.

mparsa1372 at gmail dot com ¶

Change Background Color With Rand() And Style :

matthias dot isler at gmail dot com ¶

Here is my solution:

Generate a random 5 character A-Z0-9  string

moonwalker509 at gmail dot com ¶

);      }public static function);      }public static function);      }}# eg result: «567268»# eg result: IAGRmZyJS#eg result: Gzt6syUS8M

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

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

Alex Khimch alex at khim dot removeit dot ich dot org ¶

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:

phpheader(«Content-type: image/png»);$img = imagecreatetruecolor(500,500);$ink = imagecolorallocate($img,255,255,255);

I expected to get pixel noise, but instead one can see plain diagonal lines.

A nice function to generate a random string, using any character:

Sample output: $%29zon(4f

simon at labs dot coop ¶

8 years ago

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!

szeryf. wordpress. com ¶

Much easier way to generate random string of numbers and letters:

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

//make an «empty container» or array for our keys//first count of $keys is empty so «1», remaining count is 1-6 = total 7 times//»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);    if(!;    }}

smaaps at kaldamar dot de ¶

//polar-methode by marsaglia;
            while ();
            }) * (( -);
            } while (// the check has to be done cause sometimes (1:10000)
            // values such as «1. #INF» occur and i dont know why// twelve random numbers;
            for (;
            }
            return;
     }      
}

Note that the algorithm change in version 7. 0 broke the repeatability of a random sequence initialized with a given value. For example if you have a program like:

rand — Generate a random integer

Description

If called without the optional min,
max arguments rand()
returns a pseudo-random integer between 0 and
getrandmax(). If you want a random number
between 5 and 15 (inclusive), for example, use rand(5,
15).

Note:

On some platforms (such as Windows), getrandmax()
is only 32767. If you require a range larger than 32767, specifying
min and max will allow
you to create a range larger than this, or consider using
mt_rand() instead.

Note: As of PHP 7. 0, rand() uses the same
random number generator as mt_rand(). To preserve
backwards compatibility rand() allows
max to be smaller than min
as opposed to returning false as mt_rand().

Parameters

The lowest value to return (default: 0)

The highest value to return (default: getrandmax())

Return Values

A pseudo random value between min
(or 0) and max (or getrandmax(), inclusive).

Changelog

VersionDescription

7. 0
rand() has received a bug fix for a modulo bias bug. This means that sequences generated with a specific seed may differ from PHP 7. 1 on 64-bit machines. 0
rand() has been made an alias of mt_rand().

Examples

Example #1 rand() example

The above example will output
something similar to:

Notes

min max range must
be within the range getrandmax(). (max —
min) <= getrandmax()
Otherwise, rand() may return poor-quality random numbers.

See Also

  • srand() — Seed the random number generator
  • getrandmax() — Show largest possible random value
  • mt_rand() — Generate a random value via the Mersenne Twister Random Number Generator
  • random_int() — Generates cryptographically secure pseudo-random integers
  • random_bytes() — Generates cryptographically secure pseudo-random bytes
  • openssl_random_pseudo_bytes() — Generate a pseudo-random string of bytes
Оцените статью
Добавить комментарий