php 实现随机
生成随机数
使用 rand() 函数生成指定范围内的随机整数,例如生成 1 到 100 的随机数:
$randomNumber = rand(1, 100);
mt_rand() 是更高效的替代方案,随机性更好:
$randomNumber = mt_rand(1, 100);
生成随机浮点数
通过 rand() 或 mt_rand() 结合除法生成浮点数:
$randomFloat = mt_rand(0, 1000) / 10; // 生成 0.0 到 100.0 的随机浮点数
PHP 7.2+ 可使用 random_int() 更安全地生成随机整数,再转换为浮点数。

随机数组元素
使用 array_rand() 从数组中随机返回键名:
$colors = ['red', 'green', 'blue'];
$randomKey = array_rand($colors);
$randomColor = $colors[$randomKey];
或直接使用 shuffle() 打乱数组顺序:
shuffle($colors);
$randomColor = $colors[0];
生成随机字符串
结合 str_shuffle() 和 substr() 生成固定长度随机字符串:

$chars = 'abcdefghijklmnopqrstuvwxyz';
$randomString = substr(str_shuffle($chars), 0, 5); // 5位随机字母
更复杂的场景可使用 random_bytes()(PHP 7+)生成加密安全的随机字节:
$bytes = random_bytes(5);
$randomString = bin2hex($bytes); // 转换为16进制字符串
加密安全随机数
需要高安全性时(如令牌生成),使用 random_int() 或 openssl_random_pseudo_bytes():
$secureNumber = random_int(PHP_INT_MIN, PHP_INT_MAX);
$secureBytes = openssl_random_pseudo_bytes(16);
概率权重随机
根据权重值随机选择(如抽奖系统):
$items = ['A' => 10, 'B' => 30, 'C' => 60];
$rand = mt_rand(1, array_sum($items));
foreach ($items as $key => $weight) {
if ($rand <= $weight) {
$result = $key;
break;
}
$rand -= $weight;
}






