如何处理PHP表单中的多个复选框?

Jak*_*ake 13 html php

我的表单上有多个复选框:

<input type="checkbox" name="animal" value="Cat" />
<input type="checkbox" name="animal" value="Dog" />
<input type="checkbox" name="animal" value="Bear" />
Run Code Online (Sandbox Code Playgroud)

如果我检查所有三个并点击提交,请在PHP脚本中使用以下代码:

if(isset($_POST['submit']) {
   echo $_POST['animal'];
}
Run Code Online (Sandbox Code Playgroud)

我得到"熊",即最后选择的复选框值,即使我选了所有三个.怎么得到所有3?

fat*_*zzy 23

查看我在名称中所做的更改:

<input type="checkbox" name="animal[]" value="Cat" />
<input type="checkbox" name="animal[]" value="Dog" />
<input type="checkbox" name="animal[]" value="Bear" />
Run Code Online (Sandbox Code Playgroud)

你必须把它设置为数组.

print_r($_POST['animal']);
Run Code Online (Sandbox Code Playgroud)


And*_*ter 20

<input type="checkbox" name="animal[]" value="Cat" />
<input type="checkbox" name="animal[]" value="Dog" />
<input type="checkbox" name="animal[]" value="Bear" />
Run Code Online (Sandbox Code Playgroud)

如果我检查所有三个并点击提交,请在PHP脚本中使用以下代码:

if(isset($_POST['animal'])){
    foreach($_POST['animal'] as $animal){
        echo $animal;
    }
}
Run Code Online (Sandbox Code Playgroud)


Jon*_*and 5

在字段名称后使用方括号

<input type="checkbox" name="animal[]" value="Cat" />
<input type="checkbox" name="animal[]" value="Dog" />
<input type="checkbox" name="animal[]" value="Bear" />
Run Code Online (Sandbox Code Playgroud)

在 PHP 方面,您可以像对待任何其他数组一样对待它。