Isset
Isset you use when you want to know
if a variable is defined and it is not NULL ..
Example, file1.php
if ( isset($_POST['submit']))
{
// Acciones
}
This can be useful if you want to validate that a file receives POST variables, since you could access it by url localhost / mifolder / file1.php , if you agree so you are not sending any value for POST, then it does not enter the If.
Another example:
$var = '';
// Esto evaluará a TRUE así que el texto se imprimirá.
if (isset($var)) {
echo "Esta variable está definida, así que se imprimirá";
}
Source: isset documentation
Empty
Empty is to know if a variable is empty.
"A variable is considered empty if it does not exist or if its value is equal to
FALSE. empty () does not generate a warning if the variable does not exist. "
$var = 0;
// Se evalúa a true ya que $var está vacia
if (empty($var)) {
echo '$var es o bien 0, vacía, o no se encuentra definida en absoluto';
}
What PHP considers as empty:
- "" (an empty string)
- 0 (0 as an integer)
- 0.0 (0 as a float)
- "0" (0 as a string)
- NULL
- FALSE
- array () (an empty array)
- $ var; (a declared variable, but without a value)
Source: empty documentation
Is it redundant to use isset together empty?
No, since there may be a variable defined but whose value is 0, then it is necessary to evaluate first 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 he entered it, indicating that it can not be 0 or a space, to say two examples (the format in general).
$var = 0;
if (isset($var))
echo 'La variable está definida';
if (empty($var))
echo 'La variable está definida pero está vacía';
Conclusion: isset and empty evaluate a variable in a different manner. Isset if a variable is null, empty if it is empty and can be NULL or any of the previous list.