Jake
Jake

Reputation: 161

How to handle multiple checkboxes in a PHP form?

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?

Upvotes: 16

Views: 35650

Answers (3)

Andrew Winter
Andrew Winter

Reputation: 1146

<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;
    }
}

Upvotes: 23

Jonathan Fingland
Jonathan Fingland

Reputation: 57167

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.

Upvotes: 5

fatnjazzy
fatnjazzy

Reputation: 6152

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']);

Upvotes: 25

Related Questions