Reputation:
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
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
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
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
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