表單中多個同名 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'] (數組)
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'])) { ... }
[]:只取最後值。$_POST['fruit'] **不存在**(而非空數組),需用 $_POST['fruit'] ?? [] 防錯。[],同名單選互斥,取值即為選中值。