LoginSignup
6
1

More than 5 years have passed since last update.

PHP7ではrandではなくrandom_intを使えとrecommendされる

Posted at

php7のコードの中にrandを使用している部分があり、PhpStormのrecommendが出ていたため確認をしました。

rand

簡単ですが乱数を生成してくれます。
PHP: rand - Manual

<?php
echo rand(0, 10);

あらためてマニュアルを確認すると、下記の警告が記載されていました。

警告
この関数が生成する値は、暗号学的に安全ではありません。そのため、これを暗号として使ってはいけません。暗号学的に安全な値が必要な場合は、random_int() か random_bytes() あるいは openssl_random_pseudo_bytes() を使いましょう。

random_int

暗号理論的に安全な乱数を生成してくれるといった感じでしょうか。
random_int - PHP

random_int — Generates cryptographically secure pseudo-random integers

PHP rand() vs. random_int()

まあこれだけ見るとすごろくを作る時はどっちでも良いって感じですかね。ただPhpStormにrecommend出されるのは気になります。

randとrandom_intの違いをもう少し

randは引数なしでも実行可能

<?php
echo rand(); // 689881472

echo random_int(); // fatal error

random_intはExceptionをスローする

randに文字列のaを渡すとwarningが発生しますが、random_intの場合はExceptionがスローされます。(詳細は上記のマニュアルへ)

try {
    rand('a', 2);
} catch (Error $e) {
    var_dump($e->getMessage());
}

// PHP Warning:  rand() expects parameter 1 to be integer, string given in /Users/bunta.fujikawa/workspace/laravel-exercise/test.php on line 10

try {
    random_int('a', 2);
} catch (Error $e) {
    var_dump($e->getMessage());
}

// string(60) "random_int() expects parameter 1 to be integer, string given"

速度はrandの方が早い

こちらのstackoverflowで検証している方がいました。randの方が倍近く早いそうな。
PHP rand() vs. random_int()

6
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
1