user783710
user783710

Reputation:

How to determine if checkbox is checked using PHP?

I am getting Notice: Undefined variable: myvariable when I post my form with the checkbox unchecked.

I need to check if the checkbox is not checked.

How would I do this?

Upvotes: 1

Views: 684

Answers (5)

Empty
Empty

Reputation: 457

Create hidden field before checkbox with same name on html form.


<input type="hidden" value="0" name="check"/>
<input type="checkbox" value="1" name="check"/>

In this case the value $_POST['check'] is defined always

Upvotes: 1

The Mask
The Mask

Reputation: 17427

Try this:

if(!empty($_POST["foo"])) {
    //Do something...
}

Upvotes: 0

Jason McCreary
Jason McCreary

Reputation: 72971

A common approach is to default it to some value (i.e. false) if it is not set by the form submission (i.e. $_POST). The following uses a ternary operator, adjust the values to your liking:

 $checkbox_value = isset($_POST['myvariable']) ? $_POST['myvariable'] : false;

Upvotes: 3

BraedenP
BraedenP

Reputation: 7215

If it's coming up as undefined, then do something like this:

if(isset($_POST['myvariable'])){
    //this means it's checked... do something with it
}else{
    //this means it's not checked.. do something else
}

Upvotes: 3

Dan Simon
Dan Simon

Reputation: 13117

The isset function will tell you if a variable, key in an array, or a public property in an object exists:

if (isset($variable)) {...
if (isset($array['key'])) {...

Upvotes: 4

Related Questions