16

I have multiple checkboxes on my form:

<input type="checkbox" name="animal" value="Cat" />
<input type="checkbox" name="animal" value="Dog" />
<input type="checkbox" name="animal" value="Bear" />

If I check all three and hit submit, with the following code in the PHP script:

if(isset($_POST['submit']) {
   echo $_POST['animal'];
}

I get "Bear", i.e. the last chosen checkbox value even though I picked all three. How to get all 3?

3 Answers 3

25

See the changes I have made in the name:

<input type="checkbox" name="animal[]" value="Cat" />
<input type="checkbox" name="animal[]" value="Dog" />
<input type="checkbox" name="animal[]" value="Bear" />

you have to set it up as array.

print_r($_POST['animal']);
Sign up to request clarification or add additional context in comments.

1 Comment

PHP will throw an error if none of the checkboxes are checked, because animal will not even be set.
23
<input type="checkbox" name="animal[]" value="Cat" />
<input type="checkbox" name="animal[]" value="Dog" />
<input type="checkbox" name="animal[]" value="Bear" />

If I check all three and hit submit, with the following code in the PHP script:

if(isset($_POST['animal'])){
    foreach($_POST['animal'] as $animal){
        echo $animal;
    }
}

Comments

5

use square brackets following the field name

<input type="checkbox" name="animal[]" value="Cat" />
<input type="checkbox" name="animal[]" value="Dog" />
<input type="checkbox" name="animal[]" value="Bear" />

On the PHP side, you can treat it like any other array.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.