HTML 表單多個同名輸入框(如多標籤、多圖片、複選框)只需在 name 屬性加上 [],PHP 會自動將其接收為陣列。本文示範完整流程與進階應用。
<!-- HTML 表單 -->
<form method="post" action="handle.php">
<label>標籤 (可多填)</label><br/>
<input type="text" name="tags[]" placeholder="標籤 1"><br/>
<input type="text" name="tags[]" placeholder="標籤 2"><br/>
<input type="text" name="tags[]" placeholder="標籤 3"><br/>
<button type="submit">提交</button>
</form>
<?php
// handle.php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// $_POST['tags'] 自動為陣列
$tags = $_POST['tags'] ?? [];
// 過濾空值、去除首尾空白
$tags = array_filter(array_map('trim', $tags));
if (empty($tags)) {
echo '請至少輸入一個標籤';
} else {
echo "收到 " . count($tags) . " 個標籤:<br/>";
foreach ($tags as $index => $tag) {
echo ($index + 1) . ". " . htmlspecialchars($tag) . "<br/>";
}
// 入庫範例 (標籤關聯表)
// $stmt = $pdo->prepare('INSERT INTO article_tags (article_id, tag) VALUES (?, ?)');
// foreach ($tags as $tag) $stmt->execute([$articleId, $tag]);
}
}
?>
<!-- 複選框組 -->
<input type="checkbox" name="colors[]" value="red"> 紅色
<input type="checkbox" name="colors[]" value="green"> 綠色
<input type="checkbox" name="colors[]" value="blue"> 藍色
<!-- 多選下拉選單 -->
<select name="categories[]" multiple>
<option value="tech">科技</option>
<option value="life">生活</option>
<option value="travel">旅遊</option>
</select>
PHP 端同樣收到 $_POST['colors']、$_POST['categories'] 陣列。
<div id="tagInputs">
<input type="text" name="tags[]"> <button type="button" class="remove">刪除</button>
</div>
<button type="button" id="addTag">+ 新增標籤</button>
<script>
document.getElementById('addTag').onclick = () => {
const div = document.createElement('div');
div.innerHTML = '<input type="text" name="tags[]"> <button type="button" class="remove">刪除</button>';
document.getElementById('tagInputs').appendChild(div);
};
document.getElementById('tagInputs').onclick = e => {
if (e.target.classList.contains('remove')) e.target.parentElement.remove();
};
</script>
$tags = array_unique($tags);。htmlspecialchars(),入庫前可用 HTMLPurifier。<input type="hidden" name="_token" value="= $_SESSION['csrf_token'] ?>">。// URL: /page?tags[]=php&tags[]=mysql&tags[]=nginx
$tags = $_GET['tags'] ?? []; // 同樣獲得陣列