rand

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

rand乱数を生成する

説明

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

オプションの引数 min,max を省略してコールした場合、rand() は 0 と getrandmax() の間の擬似乱数(整数)を返します。 例えば、5 から 15 まで(両端を含む)の乱数を得たい場合、 rand(5, 15) とします。

警告

この関数が生成する値は、暗号学的にセキュアではありません。そのため、これを暗号や、戻り値を推測できないことが必須の値として使っては いけません

暗号学的にセキュアな乱数が必要な場合は、Random\RandomizerRandom\Engine\Secure と一緒に使いましょう。簡単なユースケースの場合、random_int()random_bytes() 関数が、オペレーティングシステムの CSPRNG を使った、 便利で安全な API を提供します。

注意: (Windows のような)いくつかのプラットフォームでは、getrandmax() は 32767 と小さな値となっています。 32767 より広い範囲にしたい場合、 min および max を指定することで、 これより大きな範囲の乱数を生成することができます。 もしくは、 mt_rand() をかわりに使用してみてください。

注意: PHP 7.1.0 以降、rand() は、 mt_rand() と同じ乱数生成器を使います。 下位互換性を保持するために、mt_rand()false を返すのと対照的に、rand()maxmin よりも小さいことを許します。

パラメータ

min

返す値の最小値 (デフォルトは 0)。

max

返す値の最大値 (デフォルトは getrandmax())。

戻り値

min (あるいは 0) から max (あるいは getrandmax()、それぞれ端点を含む) までの間の疑似乱数値を返します。

変更履歴

バージョン 説明
7.2.0 rand() 関数のモジュロバイアスに関するバグが 修正されました。 これは、特定のシードから生成されるシーケンスが 64bit PHP 7.1 のそれとは異なる可能性があるということです。
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 までの幅を mt_getrandmax() の範囲内におさめる必要があります。 つまり、(max - min) <= mt_getrandmax() でなければいけないということです。この範囲をこえてしまうと、 rand() が返す値のランダム性が、 低品質になってしまいます。

参考

  • srand() - 乱数生成器を初期化する
  • getrandmax() - 乱数の最大値を取得する
  • mt_rand() - メルセンヌ・ツイスター乱数生成器を介して乱数値を生成する
  • random_int() - 暗号学的にセキュアな方法で、等確率に出る整数を取得する
  • random_bytes() - 暗号学的にセキュアな、ランダムなバイト列を生成する

add a note

User Contributed Notes 4 notes

up
3
play dot it at play-it dot net
1 year 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
3
relsqui at armory dot com
19 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
-5
Anonymous
3 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.
up
-11
Anonymous
14 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
To Top