關鍵在 HTML 表單中將 checkbox 的 name 設為陣列格式 name="hobby[]",PHP 即可自動接收為陣列。
<form name="myform" enctype="multipart/form-data" action="index2.php" method="post">
興趣愛好:
<input type="checkbox" name="hobby[]" value="閱讀"/> 閱讀
<input type="checkbox" name="hobby[]" value="籃球"/> 籃球
<input type="checkbox" name="hobby[]" value="旅遊"/> 旅遊
<br>
檔案上傳:<input name="myfile" type="file">
<input type="submit" value="提交" />
</form>
$result = "";
foreach ($_POST['hobby'] as $item) {
echo "
";
$result .= $item;
}
echo $result; // 例:閱讀籃球旅遊
name="hobby[]" 方括號讓 PHP 將同名欄位自動組成陣列isset($_POST['hobby']) 判斷是否有勾選項目$hobbies = $_POST['hobby'] ?? [];<input type="checkbox" name="hobby[read]" value="1"/> 閱讀 <input type="checkbox" name="hobby[sport]" value="1"/> 運動 // PHP $hobby = $_POST['hobby'] ?? []; // $hobby = ['read'=>1, 'sport'=>1] 或僅包含勾選的鍵
掌握 name="field[]" 陣列命名慣例,輕鬆處理多選框、多檔上傳等批量表單資料。