1

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?

5 Answers 5

4

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'])) {...
Sign up to request clarification or add additional context in comments.

Comments

3

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
}

Comments

3

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;

Comments

1

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

1 Comment

To clarify, in your example, $_POST['check'] would be defined; not $_POST['checkbox'].
0

Try this:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.