name=\"items[]\" 完整說明前端動態增減欄位(如多檔上傳、多筆資料輸入)時,只需在 name 屬性加上 [],PHP 即自動將同名欄位整合為陣列。
<form action="handle.php" method="post">
<input type="text" name="books[]" placeholder="書名 1">
<input type="text" name="books[]" placeholder="書名 2">
<input type="text" name="books[]" placeholder="書名 3">
<button type="submit">送出</button>
</form>
<?php
// $_POST['books'] 直接是陣列
$books = $_POST['books'] ?? [];
// 過濾空值
$books = array_filter($books, fn($v) => trim($v) !== '');
print_r($books);
/*
Array
(
[0] => 書名 1
[1] => 書名 2
[2] => 書名 3
)
*/
// 迴圈處理(如寫入資料庫)
foreach ($books as $book) {
$stmt = $pdo->prepare('INSERT INTO books (title) VALUES (?)');
$stmt->execute([$book]);
}
?>
若每筆資料有多個欄位(書名、作者、年份),使用相同索引鍵名:
<input name="books[0][title]"> <input name="books[0][author]"> <input name="books[0][year]">
<input name="books[1][title]"> <input name="books[1][author]"> <input name="books[1][year]">
...
// PHP 直接得到
$books = $_POST['books']; // 二維關聯陣列
[] 只能用於 name,不可用於 id(id 必須唯一)。 → $_FILES['files'] 為結構化陣列,需配合 array_column 整理。name="books[]" 的 input 即可,無需手動維護索引。