I have a form with a status field that allows choosing between two values 0 and 1 . If 1 is selected it enters the if .["estado"]=> string(1) "1"
if (isset($_POST['estado']) && !empty($_POST['estado']) ) {
var_dump($_POST);
exit;
}
But if 0 is selected. It does not enter the if. ["estado"]=> string(1) "0"
. What do I have to modify so that it enters the if ?
The problem is that empty returns FALSE if the value is 0 ( https://www.php.net/manual/es/function.empty.php ), maybe you can change the if to something like this:
If the data comes from a form, the input type fields
<type="text" ...>
or<select ...>
always bring a value, even if nothing is written or nothing is selected, so itisset
will always betrue
in those cases.Where if the verification must be done, it is in checkbox type fields
<input type="checkbox" ...>
A simple example form:
If nothing is written or selected and a SUBMIT is made, it
var_dump($_POST)
will have the following value:As you can see, it is
var3
necessary, because it is a checkbox, so it does not make much senseisset
in the other fields. On the other hand empty returnstrue
if the variable exists and its value is different from0
, and that is the reason why it is not entering theif
.So you have to make a strict comparison:
if($_POST['estado'] !== '')
because0 == false
and'' == false
they givetrue
. In case there is no empty third option, then nothing is needed because if or if one of the 2 values will be selected. Or you can also use<select name="var2" required>
to force select one of the 2 options with values.[ !NOTE ] Everything I've said is invalid if the fields can have the attribute
disabled
, or the DOM can be controlled by Javascript.