PHP 8.1.20 Released!

rand

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

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

Описание

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

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

Предостережение

Функция не создаёт криптографически защищённые значения и не должна использоваться для криптографических целей или целей, требующих, чтобы возвращаемые значения были недоступны для разгадывания.

Если требуется криптографически безопасная случайная последовательность, Random\Randomizer может использоваться с движком Random\Engine\Secure. Для простых случаев использования функции random_int() и random_bytes() предоставляют удобный и безопасный API, поддерживаемый CSPRNG операционной системы.

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

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

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

min

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

max

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

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

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

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

Версия Описание
7.2.0 Для rand() произведено исправление бага смещения по модулю. Это означает, что последовательности сгенерированные с конкретным начальным значением могут отличаться от сгенерированных в PHP 7.1 для 64-битных машин.
7.1.0 rand() стала синонимом функции mt_rand().

Примеры

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

<?php
echo rand(), "\n";
echo
rand(), "\n";

echo
rand(5, 15), "\n";
?>

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

7771
22264
11

Примечания

Внимание

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

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

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

add a note

User Contributed Notes 6 notes

up
4
relsqui at armory dot com
18 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,

<?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).
up
0
play dot it at play-it dot net
2 months ago
Here is a simple base64 random string function

<?php
function random_string($length) {
   
$str = random_bytes($length);
   
$str = base64_encode($str);
   
$str = str_replace(["+", "/", "="], "", $str);
   
$str = substr($str, 0, $length);
    return
$str;
}

/*
Example outputs for random_string(32)

OP0vOJEsSvr6wbgN4jIwqMMstlpMSUsl
2IHaIxD2W4VTKZuzioudbpQCALdl6Ym6
QY0eZ3QYy3OKKN6ttzbDwAwsAfkXfQ2f
jznjlPCUDbYzOTJysPP414BbdVNu4jmT
GlktgJ8JUhdH5MfQ1PHl0wnqXQlKggQs
Pb9WALM3KcGCCPBKXsPgNfy3M0Xj4aEu
AED6OTVl8aBbspdxoXvA1sT4ein8lruH
9cSbz4FhoI4qSsPZFMh0u1rWDDEgQxI2
iSBlT4K7Ad516qPXgPReSj2tii7TAK5b
DuX8HByMb2e8IdM4j49Td2JTI9Ki7o1C
*/
?>
up
-2
szeryf.wordpress.com
12 years ago
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.
up
-5
Anonymous
13 years ago
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
up
-5
Hayley Watson
10 years ago
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.
up
-6
Anonymous
2 years ago
Note that the algorithm change in version 7.1.0 broke the repeatability of a random sequence initialized with a given value. For example if you have a program like:

<?php
srand
($argv[1]);
for (
$i = 0; $i < 10; $i++) {
    echo
rand().PHP_EOL;
}
?>

It will will no longer produce the same results after version 7.1.0. This can be very important for some kinds of simulations. Hopefully you were using mt_rand() or something better all along, otherwise you will have some digging to do if you want your program to be able to repeat simulations from the pre-7.1.0 days... You will need to look in the PHP source archives to discover the algorithm they used to use and replicate it in your program.
To Top