I have a simple form I created, and in it I have the following checkbox:
<input type="checkbox" name="test">
Note: this form is being submitted to itself.
Above the form, I have the following PHP:
if (empty($_POST['test'])) {
$thevalue = 0;
} else {
$thevalue = 1;
}
var_dump($thevalue);
When I process the form, I get what I would expect. If I check the box and submit, I get int(1) if I leave it unchecked I get int(0).
In the first line of my PHP code, I wanted to replace $_POST['test'] with some simple variable.
So I added the following line above my code:
$simplevar = $_POST['test']
I then replaced the condition in my if statement to be empty($simplevar)
But when I submit the form, I get a "Notice: Undefined index:" error message
- Why is this happening?
- Assuming it’s possible to achieve what I was after (i.e. insert $_POST into $simplevar), how might I go about it?
Thanks in advance for your help!
PS: I may have a follow up to this question, but didn’t want to clutter things by jamming it all in here.
Thanks again… oh, and Merry Christmas! 😉
This happens because when you don’t check the checkbox, the browser does not send any value to server for that control when the form is submitted. Because of this,
$_POST['test']is not defined, and you tried to use it without a check as to whether it existed, so you get a warning. One of the checks thatempty()does is to see whether the value is set. So, when you use the$_POSTkeys directly inempty(), you don’t get an error, but when you try and use it in an assignment without this check, you will get the error.You can do roughly what you want to do, you just have to change the logic slightly. If you do:
…it will do what you want without the error. Using this approach,
$simplevaralways holds a boolean indicating whether or not the box was checked.