萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 獲取同名表單參數數組:checkbox 多選實現詳解

問題場景

表單中多個同名 checkbox,直接用 $_POST['arr'] 只能得到**最後一個**被選中的值:

<input type="checkbox" name="arr" value="1">
<input type="checkbox" name="arr" value="2">
<input type="checkbox" name="arr" value="3">
// $_POST['arr'] === '3' (僅最後一個)

解決方案:名稱加方括號 name="arr[]"

<input type="checkbox" name="arr[]" value="1">
<input type="checkbox" name="arr[]" value="2">
<input type="checkbox" name="arr[]" value="3">
// $_POST['arr'] === ['1', '2', '3'] (數組)

原理解析

  • PHP 解析表單數據時,遇到 name[] 格式會**自動將同名值收集為數組**。
  • 同樣適用於 select multiple、input type="file" multiple、同名文本框等。
  • $_GET、$_REQUEST 同理。

完整示例

<form method="post">
    <label><input type="checkbox" name="fruit[]" value="apple"> 蘋果</label>
    <label><input type="checkbox" name="fruit[]" value="banana"> 香蕉</label>
    <label><input type="checkbox" name="fruit[]" value="orange"> 橙子</label>
    <button type="submit">提交</button>
</form>

<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $fruits = $_POST['fruit'] ?? [];
    if (!is_array($fruits)) $fruits = [$fruits]; // 防單選情況
    echo '選中水果:' . implode(', ', $fruits);
}
?>

進階:檢測是否選中某值

if (in_array('apple', $fruits)) {
    echo '包含蘋果';
}
// 或用 isset 快速判斷(值為 key)
$fruitMap = array_flip($fruits);
if (isset($fruitMap['apple'])) { ... }

常見坑

  1. 未加 []:只取最後值。
  2. 未選中任何 checkbox:$_POST['fruit'] **不存在**(而非空數組),需用 $_POST['fruit'] ?? [] 防錯。
  3. 單選框 不需 [],同名單選互斥,取值即為選中值。
copyright © 萬盛學電腦網 all rights reserved