生成指定範圍內不重複的隨機數,核心策略有二:
shuffle() 打亂 → 截取前 N 個。array_unique() 或「翻翻法」去重 → 直到數量滿足。<?php
/**
* 產生不重複隨機整數陣列
*
* @param int $min 最小值(含)
* @param int $max 最大值(含)
* @param int $count 需要的數量
* @return array
*/
function unique_rand(int $min, int $max, int $count): array {
if ($count > ($max - $min + 1)) {
throw new InvalidArgumentException('請求數量超過範圍上限');
}
$pool = range($min, $max);
shuffle($pool);
return array_slice($pool, 0, $count);
}
// 例:1-100 取 6 個(樂透號碼)
$numbers = unique_rand(1, 100, 6);
sort($numbers);
echo implode(', ', $numbers); // 輸出如:3, 12, 25, 38, 56, 89
?>
<?php
function unique_rand_set(int $min, int $max, int $count): array {
$result = [];
while (count($result) < $count) {
$result[] = mt_rand($min, $max);
// 「翻翻法」去重:比 array_unique() 快數倍
$result = array_flip(array_flip($result));
}
shuffle($result); // 重設鍵名為 0..N-1
return $result;
}
?>
需求:25 件作品,每筆投票選 16 件不重複,補齊 200 筆。
<?php
function generate_vote(int $works = 25, int $pick = 16): string {
$vote = unique_rand(1, $works, $pick);
sort($vote);
return implode(',', $vote);
}
$votes = [];
for ($i = 0; $i < 200; $i++) {
$votes[] = generate_vote();
}
// 此處可批次寫入資料庫
// INSERT INTO votes (selection) VALUES ... (200 rows)
?>
<?php
function random_string(int $length = 10): string {
$chars = [];
// 0-9
for ($i = 48; $i <= 57; $i++) $chars[] = chr($i);
// a-z
for ($i = 97; $i <= 122; $i++) $chars[] = chr($i);
// 也可加入 A-Z
$result = '';
$lastIdx = count($chars) - 1;
while (strlen($result) < $length) {
$idx = mt_rand(0, $lastIdx);
$result .= $chars[$idx];
// 將已用字元移至尾端,下輪不再抽中(無放回抽樣)
$chars[$idx] = $chars[$lastIdx--];
}
return $result;
}
echo random_string(16); // 例:k3f9a1b7c2d5e8g4
?>
mt_rand(),速度約為 rand() 的 4 倍。array_flip(array_flip($arr))),比 array_unique() 快得多。shuffle() 重建連續鍵名,避免遍歷時鍵名斷裂。