mt_rand() 使用 Mersenne Twister 演算法產生隨機整數,速度比 rand() 快 4 倍,隨機品質更好。
int mt_rand(void)
int mt_rand(int $min, int $max)
mt_getrandmax() 之間的隨機整數$min 到 $max (含) 之間的隨機整數$max 代表範圍長度,欲得 5~15 需寫 mt_rand(5, 11)$max 代表上限值,直接寫 mt_rand(5, 15)<?php
$rand = mt_rand(0, 1); // 產生 0 或 1
if ($rand === 0) {
$array = [41, 20, 26, 29, 30];
} elseif ($rand === 1) {
$array = [38, 42, 37, 400, 444];
}
foreach ($array as $v) {
echo "$v\n";
}
mt_rand() 不具備加密安全性,不可用於 Token、密碼、Session ID 等安全敏感場景。
<?php
// PHP 7+ 專用:加密安全隨機整數
$secure_int = random_int(100000, 999999); // 6 位數驗證碼
// PHP 5 相容:使用 openssl_random_pseudo_bytes
$bytes = openssl_random_pseudo_bytes(4);
$secure_int = unpack('L', $bytes)[1] % 900000 + 100000;
| 場景 | 推薦函數 |
|---|---|
| 遊戲亂數、測試資料、非關鍵隨機 | mt_rand() |
| 驗證碼、重設密碼 Token、API Key | random_int() / random_bytes() |
| 洗牌演算法 | shuffle() (內部用 mt_rand) |