bool shuffle(array &$array)
true,失敗 false。srand()/mt_srand()。<?php
$arr = ['a' => 'Dog', 'b' => 'Cat', 'c' => 'Horse'];
shuffle($arr);
print_r($arr);
/* 可能輸出:
Array
(
[0] => Cat
[1] => Horse
[2] => Dog
)
原鍵名 a,b,c 已消失
*/
?>
<?php
function shuffle_assoc(array &$array): void {
$keys = array_keys($array);
shuffle($keys);
$result = [];
foreach ($keys as $key) {
$result[$key] = $array[$key];
}
$array = $result;
}
$data = ['id1' => 'A', 'id2' => 'B', 'id3' => 'C'];
shuffle_assoc($data);
print_r($data); // 鍵名 id1,id2,id3 保留,順序隨機
?>
<?php
$ads = [
'<a href="https://example.com/1"><img src="ad1.jpg" alt="廣告1" width="300" height="250"></a>',
'<a href="https://example.com/2"><img src="ad2.jpg" alt="廣告2" width="300" height="250"></a>',
'<a href="https://example.com/3"><img src="ad3.jpg" alt="廣告3" width="300" height="250"></a>',
'<a href="https://example.com/4"><img src="ad4.jpg" alt="廣告4" width="300" height="250"></a>',
];
shuffle($ads); // 打亂順序
// 顯示前 2 則
$displayCount = 2;
for ($i = 0; $i < $displayCount && isset($ads[$i]); $i++) {
echo $ads[$i] . "\n";
}
?>
shuffle() 為等機率。若需依權重(如廣告競價)隨機:
<?php
function weightedRandom(array $items): mixed {
// $items = ['item' => weight, ...] 權重為正整數
$total = array_sum($items);
$rand = mt_rand(1, $total);
foreach ($items as $item => $weight) {
$rand -= $weight;
if ($rand <= 0) return $item;
}
return array_key_first($items); // fallback
}
$ads = [
'ad_premium' => 50, // 50% 機率
'ad_normal' => 30, // 30%
'ad_house' => 20, // 20%
];
$selected = weightedRandom($ads);
echo "本次顯示:$selected";
?>
| 需求 | 建議函數 | 備註 |
|---|---|---|
| 打亂陣列順序 | shuffle() | O(n),原地修改,鍵名重置 |
| 保留鍵名打亂 | 自訂 shuffle_assoc() | 需額外記憶體 |
| 取 N 個不重複隨機元素 | array_rand($arr, $n) | 回傳鍵名陣列,不修改原陣列 |
| 加權隨機 | 自訂累積權重法 | 適合廣告、抽獎、A/B 測試 |
| 密碼學安全隨機 | random_int()、random_bytes() | PHP 7+,不可用 mt_rand() |
shuffle() 會重置數字鍵,**關聯鍵名會消失**。random_bytes() + bin2hex() 或 random_int()。