I have seen on many occasions when receiving data from a form the following check:
if (isset($_POST['campo1'])) {
// Resto de código
}
What if the value $_POST['campo1']
is empty?
Or on many other occasions I have seen the following check:
if (isset($_POST['campo1']) && !empty($_POST['campo1'])) {
// Resto de código
}
It is completely redundant to check the value $_POST['campo1']
at the same time with isset()
and !empty()
?
So my question is: how and when are they used isset()
and empty()
correctly?
According to the isset() documentation :
For example:
It will always return to you
true
even if the variable is empty and it should be checked with the functionempty()
:And when should you use
isset()
?As long as you want to check that the variable exists, a good example would be if you want to know if a form has been submitted :
According to the empty() documentation :
With
empty()
the following expressions are considered as empty and returntrue
:Important to know, that a warning is not generated if the variable does not exist.
This means that it
empty()
is essentially the concise equivalent of:!isset($var) || $var == false
.So if it would be redundant if we check the same variable with
isset()
andempty()
at the same time.An example how it can be used
isset()
and!empty()
at the same time when you want to receive data from a form:Isset
Isset you use it when you want to know
Example, file1.php
This can be useful if you want to validate that a file receives POST variables, since you could access by url localhost/myfolder/file1.php , if you access like this you are not sending any value by POST, so it does not enter the If.
Another example:
Source: isset documentation
Empty
Empty is to know if a variable is empty.
What PHP considers as empty:
Source: empty documentation
Is it redundant to use isset together with empty?
No, since there can be a variable defined but whose value is 0, then it is necessary to first evaluate that it is not null, and if it is not null evaluate that it is not empty in case you want to return a message to the user indicating that he must enter a value or if you entered it, indicate that it cannot be 0 or a space, to name two examples (the format in general).
Conclusion: isset and empty evaluate a variable differently . Isset if a variable is null, empty if it is empty and can be NULL or any of the previous list.
Excellent in the index you can also use this form using two statements: