處理多個同名核取方塊(checkbox)是表單開發常見需求。關鍵在於 name 屬性使用陣列語法 name="s[]",PHP 才會將勾選的值自動收集成陣列。
<form action="checkbox.php" method="post">
<input name="s[]" type="checkbox" value="3" /> 3<br>
<input name="s[]" type="checkbox" value="7" /> 7<br>
<input name="s[]" type="checkbox" value="1" /> 1<br>
<input name="s[]" type="checkbox" value="15" /> 15<br>
<input type="submit" value="送出">
</form>
// 直接取得陣列,未勾選則為空陣列或未設定
$selected = $_POST['s'] ?? [];
// 顯示原始結構
print_r($selected);
// 輸出範例:Array ( [0] => 7 [1] => 15 )
// 逐項處理
foreach ($selected as $value) {
echo "選項 {$value} 被勾選<br>";
}
$selected = $_POST['s'] ?? [];
if ($selected) {
$placeholders = implode(',', array_fill(0, count($selected), '?'));
$sql = "INSERT INTO user_options (user_id, option_id) VALUES " .
implode(',', array_fill(0, count($selected), "({$userId}, ?)"));
$stmt = $pdo->prepare($sql);
$stmt->execute($selected);
}
name="s[]" 的方括號 → 只會收到最後一個值isset($_POST['s']) 直接迴圈 → 發生警告