The isset
checks if a variable has been defined / initialized, is not checked if it has a value.
isset
will always return true
to $_POST
because it goes always be defined, but it may be empty, which is probably the source of your problem.
See the $_POST
documentation:
This is a superglobal , or global automatic, variable. This
simply means that it is available in all scopes by the
script .
To check if the variable is empty, use empty
:
$titulo = empty($_POST['titulo']) ? 'Sem titulo' : $_POST['titulo'];
Similar to isset
, empty
also checks if the variable has been initialized, but does not issue a warning . What is considered empty by empty
:
-
""
(an empty string )
-
0
( 0 as an integer)
-
0.0
( 0 as a floating point)
-
"0"
( 0 as a string )
-
NULL
-
FALSE
-
array()
(a% empty%)
-
array
(a declared variable, but no value)
According to the documentation , $var;
is essentially equivalent to empty
.
Another alternative is to use !isset($var) || $var == false
and a condition to check if variable is not empty:
$titulo = isset($_POST['titulo']) && $_POST['titulo'] !== '' ?
$_POST['titulo'] : 'Sem titulo';
See also: